|
|
|
|
|
# heapify
for i = n/2:1, sink(i,n)
invariant: a[1,n] in heap order
# sortdown
for i = 1:n,
swap a[i,n-i+1]
sink(1,n-i)
invariant: a[n-i+1,n] in final position
end
Heap sort is simple to implement, performs an O(n·lg(n)) in-place sort, but is not stable.
In the code above, sink(i,n) sinks element i in a heap that occupies a[1..n]. The first loop puts the array into heap order. The second loop, the "sortdown", repeatedly extracts the maximum and restores heap order. The array is put into heap order using the bottom-up heapify method, which takes Ω(n) time. The sortdown takes Ω(n·lg(n)) time.
Both phases are slightly adaptive, though not in any particularly useful manner. In the nearly sorted case, the heapify phase destroys the original order. In the reversed case, the heapify phase is as fast as possible since the array starts in heap order, but then the sortdown phase is typical. In the few unique keys case, there is some speedup but not as much as in shell sort or 3-way quicksort.
to restart the animations.
Algorithms in Java, Parts 1-4, 3rd edition by Robert Sedgewick. Addison Wesley, 2003.