Heapify

### Chapter: Heaps ...Section: Heapify

Suppose we have a complete binary tree somewhere whose subtrees are heaps. In the following complete binary tree, the subtrees of 6 are heaps:

The Heapify procedure alters the heap so that the tree rooted at 6's position is a heap. Here's how it works. First, we look at the root of our tree and its two children.

We then determine which of the three nodes is the greatest. If it is the root, we are done, because we have a heap. If not, we exchange the appropriate child with the root, and continue recursively down the tree. In this case, we exchange 6 and 8, and continue.

Now, 7 is greater than 6, so we exchange them.

We are at the bottom of the tree, and can't continue, so we terminate.

Here is a somewhat more formal description of the algorithm for performing heapify on a complete binary tree rooted at n whose subtrees are heaps.

```if n has no children
terminate
let x be the max of {key(n), key(left(n)), key(right(n))}
if x = key(n)
terminate
otherwise
exchange n and the node whose key is x
heapify the tree rooted at n's new position
```

## Exercise 3

Again, the title says it all. Prove the Heapify algorithm above correct.

rhyspj@gwu.edu