6.2 维护堆的性质

  1. l = left(i)
  2. r = right(i)
  3. if l <= A.heap-size and A[l] > A[i]
  4. largest = l
  5. else largest = i
  6. if r <= A.heap-size and A[r] > A[largest]
  7. largest = r
  8. if largest != i
  9. exchange A[i] with A[largest]
  10. maxHeapify(A, largest)

时间复杂度:O(h),h为树高

6.3 建堆

  1. A.heap-size = A.length
  2. for i = Math.floor(A.length / 2) downto 1
  3. maxHeapify(A, i)

6.4 堆排序算法

  1. buildMaxHeap(A)
  2. for i = A.length downto 2
  3. exchange A[1] with A[i]
  4. A.heap-size = A.heap-size - 1
  5. maxHeapify(A, 1)