Heapify(A, i){
l <- left(i)
r <- right(i)
if l <= heapsize[A] and A[l] > A[i]
then largest <- l
else largest <- i
if r <= heapsize[A] and A[r] > A[largest]
then largest <- r
if largest != i
then swap A[i] <-> A[largest]
Heapify(A, largest)
}
Buildheap(A){
heapsize[A] <- length[A]
for i <- |length[A]/2| downto 1
do Heapify(A, i)
}
Heapsort(A){
Buildheap(A)
for i <- length[A] downto 2
do swap A[1] <-> A[i]
heapsize[A] <- heapsize[A] - 1
Heapify(A, 1)
}
The entire HeapSort method consists of two major steps:
STEP 1: Construct the initial
heap using adjust (N/2) times on all non-leaf nodes.
STEP 2: Sort by swapping and
adjusting the heap (N-1) times.
In step 2, since the largest element of the heap is always at the root, after the initial heap is constructed, the root value is swapped with the lowest, rightmost element. This node corresponds to the last element of the array and so after the swapping the righmost element of the array has the largest value, which is what we want it to have. Consequently, the rightmost element is correctly place, and so the corresponding node becomes a light gray in the tree display depicting the heap. Also, the elements (nodes) chosen for swapping at this point of the algorithm are shown as yellow nodes.
Thereafter, since the value
of the lowest, rightmost node has moved up to the root, the heap property
of the rest of the heap (minus the gray nodes) has been disturbed. Consequently,
now the Heapify process is applied to the rest of the heap (treating the
light gray nodes as though they were no longer a part of the heap). Once
the rest of the heap is again converted to a proper heap, the swapping
process as described in the previous paragraph, followed by the Heapify
process is applied again. This continues until the root node of the heap
turns light gray - i.e., the root has its correct value. Then, the array
is sorted.