16 --> 14
16 --> 10
14 --> 8
14 --> 7
10 --> 9
10 --> 3
8 --> 2
8 --> 4
7 --> 1
=> [16,14,10,8,7,9,3,2,4,1]
// 노드 i를 루트로하는 서브트리를 heapify 한다.
MAX-HEAPIFY(A, i) {
if there is no child of A[i]
return;
k = index of the biggest child of i;
if (A[i] < A[k]) {
exchange A[i] and A[k]
MAX-HEAPIFY(A, k)
}
}
MAX-HEAPIFY(1) // 초기 호출
heap-size[A] = A.length
for i = (A.length / 2) to 1
do MAX-HEAPIFY(A, i)
HEAPSORT(A)
Build MAX-HEAP(A) // O(N)
for i = heap_size downto 2 do // O(N)
exchange A[1] and A[i]
heap_size = heap_size - 1;
MAX-HEAPIFY(A, 1) // O(logN)