[   ^ to index...   |   <-- previous   ]

Heap operations

Heaps have two important operations: create, and pop_max.

Making a heap

How do we turn an ordinary array of values into a heap? Well, there are two ways: we can do it top-down, or bottom-up. The bottom-up way is easier to present.

First: consider the case when we have left and right subtrees that are heaps, but the root node may be less than its left or right children.

[diagram of a near-heap]

We can easily see that all we have to do is "percolate" the given item down to its proper level in the heap. We do this by repeatedly exchanging the item with the larger of its children, until it is larger than all its children. We call this operation "heapify".

Now, we can turn any arbitrary array into a heap by starting halfway down the array (why halfway?) and repeatedly "heapifying" the current item.

pop_max

The pop_max operation is simple:

  1. Remove the root.
  2. Place the last leaf (the item at the end of the array) at the root and shrink the logical array by one element. The array is now a heap, except for the root node.
  3. Re-heapify by percolating this element down.

Using a heap to sort

With these pieces, heapsort is also dead simple:

  1. Build a heap from the array.
  2. While the heap is not empty, swap the root and the last element, shrink the heap by one, and re-heapify.

Understanding why this works, however, takes some thought.


Last modified: Tue Aug 8 10:27:20 PDT 2000