📅  最后修改于: 2021-01-12 03:38:28             🧑  作者: Mango
Heapify方法重新排列数组的元素,第i个元素的左和右子树遵循heap属性。
Algorithm: Max-Heapify(numbers[], i)
leftchild := numbers[2i]
rightchild := numbers [2i + 1]
if leftchild ≤ numbers[].size and numbers[leftchild] > numbers[i]
largest := leftchild
else
largest := i
if rightchild ≤ numbers[].size and numbers[rightchild] > numbers[largest]
largest := rightchild
if largest ≠ i
swap numbers[i] with numbers[largest]
Max-Heapify(numbers, largest)
当提供的数组不遵循heap属性时,将基于以下算法Build-Max-Heap(numbers [])构建Heap 。
Algorithm: Build-Max-Heap(numbers[])
numbers[].size := numbers[].length
fori = ⌊ numbers[].length/2 ⌋ to 1 by -1
Max-Heapify (numbers[], i)