Replace the root of the heap with the last element on the last level.
Compare the new root with its children; if they are in the correct order, stop.
If not, swap the element with one of its children and return to the previous step. (Swap with its smaller child in a min-heap and its larger child in a max-heap.)
Max-Heapify (A, i):
left = 2*i
right = 2*i+1
largest = i
if left <= heap_length[A] and A[left] > A[largest] then:
largest = left
if right <= heap_length[A] and A[right] > A[largest] then:
largest = right
if largest != i then:
swap(A[i], A[largest])
Max-Heapify (A, largest)
构造堆的算法描述如下:
Build-Max-Heap (A):
heap_length[A] = length[A]
// 这块其实就是对二叉树中所有非叶子节点进行“下移”操作,从最底层向最上构造堆
for each index i from floor(length[A]/2) downto 1 do:
Max-Heapify (A, i)
这个构造堆的算法的时间复杂度分析比较复杂一些,具体的分析可参考Building a heap,这里说一下分析的思路:分析这个时间复杂度,我们知道一次“下移”操作的时间复杂度是,时间复杂度与树高度有关,然后分析每一层的时间复杂度,再分析每一层最多有多少个节点,最后将所有层累加起来就得到了,式子比较复杂,还需要级数化简等步骤。