next up previous index
Next: Sorting by removal Up: Building the heap Previous: The code   Index

Efficiency

What we have achieved, as a result of this routine, is to convert the original array into a heap. This was done by permuting elements of the original array to obtain
$[31, 35, 40, 10, 42]
\mapsto
[42, 35, 40, 10, 31]$
Note the final array is not yet sorted, although we know that the first element has to be the largest. But that wasn't the point. Sorting proper will begin when we remove items from the heap.

You could achieve the same result by inserting elements one at a time into the heap. But the worst case performance of that algorithm could then be ${\cal
O}(n\log n)$, whereas it can be shown that the method just described is always no worse than ${\cal O}(n)$. You ought not to get too excited about this result. Sorting proper takes place by removal of items from the heap, and that will generally be ${\cal
O}(n\log n)$. But it is certainly worth using the more efficient algorithm, especially as the total code is actually shorter.



Peter Williams 2005-06-07