一直都背不熟这三个heap最基本的概念,用中英写了一次加强记忆
What is Percolate Up?
the element need to be moved up to maintain the heap’s property. e.g., when offering a new element into the heap. 当一个元素被offer进去了heap之后,heap需要维持当前的规则(min heap 或者 max heap),从而移动里面的元素
How to maintain? compare the element with its parent, move it up when necessary. Do this until the element does not need to be moved. 当offer进去了heap之后,因为heap是类似一个complete binary tree,所以新的元素肯定是在最后一层最右。如例子:
1
/ \
2 8
/ \ / \
4 6 8.5 9
/ \
5 1.5 <--新的元素
对比这个新进来的元素和其父母,适当的矫正它所需要在的位子。如例子,1.5是不应该在4下面因为比4大
1.5 -> 4
1
/ \
2 8
/ \ / \
1.5 6 8.5 9
/ \
5 4
然后1.5再和它的父母对比,因为1.5比2小,所以还是会swap位置
1.5 -> 2
1
/ \
1.5 8
/ \ / \
2 6 8.5 9
/ \
5 4
The comparison is repeated until the parent is larger than or equal to the percolating element. 我们会一直对比直到新插入进来的元素大于或者等于父母
由此就完成了一次percolate up,而它的时间复杂度是O(log n)因为最坏情况下我们需要每一层在从插入节点到根节点的路径上swap一次。
What is Percolate Down?
the element need to be moved down to maintain the heap’s property. e.g., when poll the root element from the heap. 当一个元素被poll出来heap之后,heap需要维持当前的规则(min heap 或者 max heap)。从而移动里面的元素
How to maintain? compare the element with its two children, if the smallest one of the two children is smaller than the element, swap the element with that child. Do this until the element doesn’t need to be moved. 当被移除了root之后,把最后一个元素移到root(也就是最后一层最右)。例子:
1 <-- 被移除了的root
/ \
2 8
/ \ / \
4 6 8.5 9
/ \
5 10 <--- 最后最右一个元素
========poll了之后=========
10 <-- 新的的root
/ \
2 8
/ \ / \
4 6 8.5 9
/
5
然后需要开始维持整个heap的规则,我们先看当前root和它的两个孩子并矫正。(因为10是比2和8大的,我们的宗旨是如果其最小的孩子比当前root小,那么就swap)
2
/ \
10 8
/ \ / \
4 6 8.5 9
/
5
然后再看10和当前的两个孩子,可见4是最小的,所以swap
2
/ \
4 8
/ \ / \
10 6 8.5 9
/
5
再对比10和当前的孩子,5是最小的,所以swap
2
/ \
4 8
/ \ / \
5 6 8.5 9
/
10
完成。不是所有的percolate down都会让元素走到最后,但是这个percolate down会一直跑直到the new ‘root’ element checked with its two children and confirm that there is no need to go further down because the ‘root’ element is smaller than its two children. 这个新的’root’元素比当前自己两个孩子都要小
时间上也是O(log n)
Heapify
Definition: convert an array to heap in O(n) time
将一个array变换成heap
For each node that has at least one child, we perform percolateDown() action in the order of from the nodes on the deepest level to the root.
对每个至少有一个孩子的节点,从下往上percolateDown()
e.g., {10, 11, 7, 2, 8, 4, 6, 13, 3}
Original Tree: 10
/ \
11 7
/ \ / \
2 8 4 6
/ \
13 3
we start on bottom parent first.
After percolateDown() on 2:
10
/ \
11 7
/ \ / \
2 8 4 6
/ \
13 3
After percolateDown() on 7:
10
/ \
11 4
/ \ / \
2 8 7 6
/ \
13 3
After percolateDown() on 11:
10
/ \
2 4
/ \ / \
3 8 7 6
/ \
13 11
After percolateDown() on 10:
2
/ \
3 4
/ \ / \
10 8 7 6
/ \
13 11