Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
The BuildHeap method shown in Program transforms an unsorted array into a max heap. It does so by calling the PercolateDown method for .
Program: HeapSorter class BuildHeap method.
Why does BuildHeap start percolating at ? A complete binary tree with n nodes has exactly leaves. Therefore, the last node in the array which has a child is in position . Consequently, the BuildHeap method starts doing percolate down operations from that point.
The BuildHeap visits the array elements in reverse order. In effect the algorithm starts at the deepest node that has a child and works toward the root of the tree. Each array position visited is the root of a subtree. As each such subtree is visited, it is transformed into a max heap. Figure illustrates how the BuildHeap method heapifies an array that is initially unsorted.