next up previous index
Next: Preliminaries Up: Data Structures Previous: Code and Demonstration   Index


Heap Sort

Array sorting is a fundamental operation in many applications. The requirement is to sort n elements of an array

a[0], ..., a[n-1]
into increasing order. For this to make sense, the elements must be comparable with respect to order. So we assume that array elements implement the Comparable interface. Note that the array itself may be of length greater than n. The specification only requires that the first n elements should be sorted.

There are a number of efficient algorithms which run in ${\cal
O}(n\log n)$ time on average. Binary heaps provide such an algorithm, and one which has a number of attractive features. A simple implementation would be to insert the array elements, one by one, into a priority queue, implemented by a binary heap, and then to remove them one by one. It is true they would then come out in reverse order, but it would be simple to revise the binary heap code to implement an ``inverse priority'' queue in which the smallest element emerges first.

There are, however, two related ways in which we can improve on this simple algorithm:

  1. The simple algorithm requires auxiliary storage for the heap. In fact it is possible to use the original array itself as the heap. This would provide a genuinely ``in-place'' sorting routine.
  2. Insertion of the array elements one by one, and restoring the heap order property after each insertion, is not the most efficient way of building the heap. That was necessary for the priority queue implementation, since the next method to be called might be the remove method, so the heap had to be properly ordered at all times. In our case we only want to remove elements after all of them have been inserted. In that case, it turns out there is a more efficient way of building the heap.



Subsections
next up previous index
Next: Preliminaries Up: Data Structures Previous: Code and Demonstration   Index
Peter Williams 2005-06-07