Heapsort
Heapsort is what you get when you put the last two lessons together. Build a max-heap; the largest value is now at position 0. Swap it with the last position, where it belongs, shrink the heap by one, and repair the root with a sift-down. Repeat. The result is a sort that is in the worst case and in place, using no memory besides the array and a few variables. Merge sort has the first property but not the second, and quicksort has the second but not the first.
The algorithm
HEAPSORT(a)
1 BUILD-MAX-HEAP(a)
2 for end = n - 1 down to 1
3 swap a[0] and a[end] // the maximum of a[0:end+1] goes to its final place
4 SIFT-DOWN(a, 0, end) // the heap is now a[0:end]The Python version prints the array after the heap is built and after each extraction, the frames that say "Max-heap built" and "Move the maximum … to position …" followed by the repairing sift-down. A vertical bar separates the heap from the sorted suffix.
def sift_down(a, i, size):
while True:
l, r = 2 * i + 1, 2 * i + 2
largest = i
if l < size and a[l] > a[largest]: largest = l
if r < size and a[r] > a[largest]: largest = r
if largest == i:
return
a[i], a[largest] = a[largest], a[i]
i = largest
def show(a, end):
return (" ".join(map(str, a[:end])) + " | " + " ".join(map(str, a[end:]))).rstrip()
def heapsort(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sift_down(a, i, n)
print(f"heap built: {show(a, n)}")
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
print(f"move {a[end]:>2} to pos {end}: {show(a, end)}")
sift_down(a, 0, end)
print(f" repaired: {show(a, end)}")
return a
print(heapsort([4, 10, 3, 5, 1, 8]))heap built: 10 5 8 4 1 3 |
move 10 to pos 5: 3 5 8 4 1 | 10
repaired: 8 5 3 4 1 | 10
move 8 to pos 4: 1 5 3 4 | 8 10
repaired: 5 4 3 1 | 8 10
move 5 to pos 3: 1 4 3 | 5 8 10
repaired: 4 1 3 | 5 8 10
move 4 to pos 2: 3 1 | 4 5 8 10
repaired: 3 1 | 4 5 8 10
move 3 to pos 1: 1 | 3 4 5 8 10
repaired: 1 | 3 4 5 8 10
[1, 3, 4, 5, 8, 10]
In C++
The same algorithm on a plain array range, sorting in place:
#include <cstdio>
#include <utility>
#include <vector>
void sift_down(std::vector<int>& a, int i, int size) {
for (;;) {
int l = 2 * i + 1, r = 2 * i + 2, largest = i;
if (l < size && a[l] > a[largest]) largest = l;
if (r < size && a[r] > a[largest]) largest = r;
if (largest == i) return;
std::swap(a[i], a[largest]);
i = largest;
}
}
void heapsort(std::vector<int>& a) {
int n = static_cast<int>(a.size());
for (int i = n / 2 - 1; i >= 0; --i) sift_down(a, i, n);
for (int end = n - 1; end > 0; --end) {
std::swap(a[0], a[end]);
sift_down(a, 0, end);
}
}
int main() {
std::vector<int> a = {4, 10, 3, 5, 1, 8};
heapsort(a);
for (std::size_t i = 0; i < a.size(); ++i) std::printf(i ? " %d" : "%d", a[i]);
std::printf("\n");
std::vector<int> b = {38, 27, 43, 3, 9, 82, 10, 3, 27};
heapsort(b);
for (std::size_t i = 0; i < b.size(); ++i) std::printf(i ? " %d" : "%d", b[i]);
std::printf("\n");
}1 3 4 5 8 10
3 3 9 10 27 27 38 43 82
Correctness
Invariant. At the start of each iteration of the loop in line 2, with index : is a max-heap holding the smallest values of the input, and holds the largest values in sorted order.
- Initialization. : the whole array is a heap (line 1), and the sorted suffix is empty.
- Maintenance. The root is the maximum of the heap, which by the invariant is at most every value in the suffix. Swapping it to position extends the sorted suffix by one value that is at most everything after it. The swap puts some other value at the root, but the subtrees of position 0 inside are untouched heaps, so the precondition of sift-down holds and line 4 restores a heap on .
- Termination. The loop ends with : holds the largest values sorted, and is the smallest. The array is sorted, and since the algorithm only swaps, it is a permutation of the input.
Running time
Building the heap costs (Building a Heap in Linear Time). Each of the sift-downs from the root costs , so heapsort runs in
time in the worst case. The extraction phase dominates: unlike construction, these sift-downs all start at the top, and on most inputs the value moved to the root is a small one from the bottom, so it sinks nearly all the way back down. Counting comparisons shows it. The leading term of heapsort's comparison count is , about twice what merge sort needs, on almost every kind of input; at moderate sizes a negative linear term is still visible, so the measured counts sit somewhat below .
import math, random
def heapsort_counted(a):
a = list(a)
n = len(a)
count = 0
def sift_down(i, size):
nonlocal count
while True:
l, r, largest = 2 * i + 1, 2 * i + 2, i
if l < size:
count += 1
if a[l] > a[largest]: largest = l
if r < size:
count += 1
if a[r] > a[largest]: largest = r
if largest == i:
return
a[i], a[largest] = a[largest], a[i]
i = largest
for i in range(n // 2 - 1, -1, -1):
sift_down(i, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(0, end)
assert a == sorted(a)
return count
rng = random.Random(3)
n = 4096
inputs = {
"random": rng.sample(range(n), n),
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1)),
"all equal": [7] * n,
}
print(f"n = {n}, 2 n lg n = {2 * n * math.log2(n):.0f}, lg(n!) = {math.lgamma(n + 1) / math.log(2):.0f}")
for name, data in inputs.items():
c = heapsort_counted(data)
print(f"{name:>9}: {c:>6} comparisons = {c / (n * math.log2(n)):.2f} n lg n")n = 4096, 2 n lg n = 98304, lg(n!) = 43250
random: 85657 comparisons = 1.74 n lg n
sorted: 88835 comparisons = 1.81 n lg n
reversed: 82304 comparisons = 1.67 n lg n
all equal: 12282 comparisons = 0.25 n lg n
Random, sorted and reversed inputs all cost between and times , against here for the best possible: heapsort hardly notices the input order. (Reversed input is already a max-heap, which saves only the cheap construction phase.) Only many equal keys help, because then sift-down stops immediately; with all keys equal it never swaps at all.
In practice: A variant called bottom-up heapsort sinks the hole to a leaf with one comparison per level (just "which child is larger?") and then lets the value climb back the short distance it overshot. That brings the comparison count close to . Heapsort is rarely the fastest sort on modern hardware, because its memory accesses jump around the array and defeat the cache, but its guaranteed with memory makes it the safety net inside introsort (Quicksort in Practice).
Heapsort is not stable
The swap in line 3 sends the root across the whole heap, past any number of equal keys. Sorting pairs by their first component shows equal keys changing order:
def heapsort_by_key(a, key):
n = len(a)
def sift_down(i, size):
while True:
l, r, largest = 2 * i + 1, 2 * i + 2, i
if l < size and key(a[l]) > key(a[largest]): largest = l
if r < size and key(a[r]) > key(a[largest]): largest = r
if largest == i: return
a[i], a[largest] = a[largest], a[i]
i = largest
for i in range(n // 2 - 1, -1, -1):
sift_down(i, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(0, end)
return a
records = [(2, "a"), (1, "b"), (2, "c"), (1, "d"), (2, "e")]
print("heapsort: ", heapsort_by_key(list(records), key=lambda r: r[0]))
print("stable sorted:", sorted(records, key=lambda r: r[0]))heapsort: [(1, 'b'), (1, 'd'), (2, 'c'), (2, 'e'), (2, 'a')]
stable sorted: [(1, 'b'), (1, 'd'), (2, 'a'), (2, 'c'), (2, 'e')]
To make any sort stable, sort the pairs instead of the keys: ties are then broken by position. That costs extra memory, which removes heapsort's main advantage.
Test yourself
What is heapsort's worst-case running time, and how much extra memory does it need?
- time, extra memory
- time, extra memory
- time, extra memory
- time, extra memory
After the iteration with in heapsort on 6 values, which positions are guaranteed to hold their final values?
- only position 5
- positions 4 and 5
- positions 0 to 4
- none yet
Why does heapsort make roughly comparisons even on sorted input?
- Because it first reverses the input
- Because each extraction moves a small value from the bottom to the root, and it sinks back almost to the bottom at two comparisons per level
- Because building the heap costs
- It doesn't: sorted input costs