一直都背不熟这三个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