Does heapify(int rootIndex) only builds heap for the heap rooted at the input rootIndex?

77 Views Asked by At

So the heapify operation is something like this (say we are discussing binary max heaps).

maxHeapify(int rootIndex){
    int largestIndex = rootIndex;
    int largest = heap[rootIndex];
    if (largest < heap[leftChildIndexOf(rootIndex)]){
        largestIndex = leftChildIndexOf(rootIndex);
    }
    if (largest < heap[rightChildIndexOf(rootIndex)]){
        largestIndex = rightChildIndexOf(rootIndex);
    }
    if (largestIndex != rootIndex){
        //Swap heap[rootIndex] & heap[largestIndex]
        maxHeapify(largestIndex);
    }

}

This heapify operation has an assumption that the max heap properties are being satisfied everywhere except possibly at the input rootIndex. Now, consider a scenario like this,

          6
         / \
        5   4
      /   \
    7      6
   / \    / \
  6   6  6   6

Clearly, the max heap property is being violated where 5 is present. If we run maxHeapify on the heap rooted at 5, the resulting heap becomes,

          6
         / \
        7   4
      /   \
    5      6
   / \    / \
  6   6  6   6

And then the maxHeapify function recursively moves down to the heap rooted at 5 now, and it finally becomes,

          6
         / \
        7   4
      /   \
    6      6
   / \    / \
  5   6  6   6

However, the max heap property is also being violated at 7, but since maxHeapify recursively moves down, it doesn't touch that.

Is it valid to assume that maxHeapify(int rootIndex) will only ensure that at the end of all recursive calls, the heap rooted at rootIndex will satisfy max heap property, but nothing can be said about the heap rooted at parentIndexOf(rootIndex)?

1

There are 1 best solutions below

0
Matt Timmermans On

That heapify operation does even less than that. It cannot fix arbitrary errors in the heap rooted at rootIndex.

The only problem it can fix is a root that is too small -- the two subtrees of the root must already satisfy the heap property in order for it to work correctly.