Imperative Heaps

January 25, 2013

When I made the list of heap algorithms in the previous exercise, I realized that we don’t have an implementation of what is probably the most common form of heaps, the mutable heaps of imperative languages implemented in an array x. The basic idea is to arrange the items in the array so the largest is at index 1, and each item xi is greater than x2i and x2i+1 (that’s a max-heap—a min-heap with the smallest item at the root has the sense of the comparison reversed).

A heap stored sub-array x1..n−1 is unlikely to remain a heap if a new item is placed at xn. The siftup function restores the heap property to x1..n by repeatedly swapping the item at xn with its parent at xn/2 until it reaches its proper place in the heap.

The siftdown operation takes a heap stored in a sub-array x1..n in which the item at x1 is out of place and restores the heap property to x1..n by repeatedly swapping the out-of-order item with its lesser child until it reaches the proper place in the array.

Given the siftup and siftdown operations, sorting an array is easy. First, for each item from the second to the last, sift it up to its proper position, forming a heap in x1..n. Then, swap each item from the last to the second with the first item and sift the new first item down to its proper position in the heap.

Your task is to write functions that implement the siftup, siftdown, and heapsort procedures. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.


Pages: 1 2