44B. Building an Initial Heap

Suppose that A is an array of n integers, in an arbitrary order. We would like to reorder it to make it into a heap.

It suffices to work from the bottom of the heap to the top. At each step, we do reheapDownMax to push a value down into the two max-heaps below it. (They will be max-heaps because the process works from the bottom to the top.) After the reheapDownMax step at a given node, that node will be the root of a max-heap.

There is no need to do anything at leaves, since the values in leaves cannot move any lower in the heap. So we can start at the parent of the last node in the heap, which is the node with the largest index that has at least one child. Here is an illustration.

Here is an implementation of buildHeap based on those ideas.

  // buildHeap(A,n) reorders A[0,...,n-1] so that it 
  // statisfies the ordering requirement of a max-heap.

  void buildHeap(int A[], const int n)
  {
    for(int i = parent(n-1); i >= 0; i--)
    {
      reheapDownMax(i, A, n);
    }
  }

Exercises

  1. Simulate buildHeap on the following array. Show both the array and the heap (as a tree) at the beginning and after each iteration of the loop.

    Answer

  2. An alternative way to perform buildHeap is to keep the array in the following form.

    The max-heap part can be enlarged by one by inserting the first value in the unlooked-at part into the max-heap. That is just a matter of doing a reheapUpMax step starting at index k, then adding 1 to k because the heap is one larger. Write an implementation of this version of buildHeap.

    Answer

  3. Using big-O notation, analyze how much time the implementation of buildHeap in the previous question takes, as a function of n, in the worst case. Answer