44C. Sorting Using Heaps

To sort an array of size n, our goal is to maintain a loop invariant: keep the array in a state where the first k members are a max-heap and the last nk members are in the correct position for sorted order.

That is easy to get started by calling buildHeap and setting k = n. Then the entire array is a max-heap and none of the values are known to be in correct position.

The largest value in the max-heap is at its root, which is at index 0 in the array. If we swap that value with the last position (index k−1) in the max-heap, then that value is in the correct position.

Now the finished part is one larger and the heap is one smaller. But the heap is not ordered correctly, since the new value at index 0 (the root of the heap) is too small. So we call reheapDownMax to push it down into the now-smaller max-heap. Here is the full algorithm to sort an array.

  // heapSort(A, n) sorts A[0,...,n-1] into nondescending order.

  void heapSort(int A[], const int n)
  {
    buildHeap(A, n);
    int k = n;
    while(k > 1)
    {
      swap(A[0], A[k-1]);
      k--;
      reheapDownMax(0, A, k);
    }
  }
When there is just one value left in the max-heap, it must be the smallest value in the array, and the sort is finished. Here is a simulation of Heap Sort, starting after the buildHeap step. The red line separates the max-heap from the values that have been placed in their correct positions.


Exercises

  1. Simulate heapSort on the following array. It is already a heap, so skip the buildHeap step. Just simulate the loop. Show the array and the heap (as a tree) at the beginning and after each iteration of the loop.

    Answer