Heapsort

A file K1...Kn is a maxheap if, for 1 < j ≤ n,   K[ j / 2 ] ≥ Kj

This is known as the heap criteria.

The algorithm proceeds:
1. Transform the arbitrary input file to become a maxheap.
2. Exchange the first and last cells. Now, the last cell has its correct final contents and is part of the solution.
3. Fix up the rest of the file to become a (smaller) heap and iterate.

Transforming a file to become a maxheap: Initially, the nodes at the lowest level (each of which is a subtree of height 0) satisfy the heap criteria.

We shall iterate on rearranging nodes so that the next higher level, h, will also satisfy the heap criteria.

A node at level h should be greater than either of its sons. If it is, then the subtree headed by that node saisfies the heap criteria. If not, exchange that node (the root of a subtree of height h) with the larger of its sons. This might destroy the worthiness of a subtree of height h-1, so that subtree has to be fixed up.

The following implementation uses arrays indexed 1 to n. You may wish to implement arrays indexed 0 to n-1.

HEAPSORT(n)
    BUILDHEAP(n)
    for size := n downto 2 do
       exchange A[1] <-> A[size]
       HEAPIFY(1, size-1)

BUILDHEAP(n)  transforms input into heap
    for i := n downto 1 do
       HEAPIFY(i,n)

HEAPIFY(i,n)  assumes i+1...n are okay, makes i...n okay
    j := i
       while (j ≤ n/2) do
          the sons of j are 2j and 2j+1
          [ if n=2j, only one son ]
          k := son of j with larger value
          if (A[k] > A[j]) then
             A[k] <-> A[j]
             j := k
          else
             j := n

Time analysis: For a heap of height h, HEAPIFY takes time TH(h) ≤ TH(h-1) + c. Therefore, TH(h) = O(h).

BUILDHEAP calls HEAPIFY once for each node. There are at most n/2i nodes of height i.
Therefore, T(n) ≤ ∑i =1 to h [ TH(i) . (number of nodes at height i) ] ≤ ∑i =1 to h c . i . n/2i = O(n).


Dan Hirschberg
Last modified: Oct 28, 2003