TExcelTAD

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 O(nlg⁡n)O(n \lg n) 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

text
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.

python · try it yourself
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:

cpp · try it yourself
#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 endend: a[0:end+1]a[0:end+1] is a max-heap holding the end+1end + 1 smallest values of the input, and a[end+1:n]a[end+1:n] holds the n−end−1n - end - 1 largest values in sorted order.

  • Initialization. end=n−1end = n - 1: the whole array is a heap (line 1), and the sorted suffix is empty.
  • Maintenance. The root a[0]a[0] is the maximum of the heap, which by the invariant is at most every value in the suffix. Swapping it to position endend 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 a[0:end]a[0:end] are untouched heaps, so the precondition of sift-down holds and line 4 restores a heap on a[0:end]a[0:end].
  • Termination. The loop ends with end=0end = 0: a[1:n]a[1:n] holds the n−1n - 1 largest values sorted, and a[0]a[0] 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 O(n)O(n) (Building a Heap in Linear Time). Each of the n−1n - 1 sift-downs from the root costs O(lg⁡n)O(\lg n), so heapsort runs in

O(n)+(n−1)⋅O(lg⁡n)=O(nlg⁡n)O(n) + (n - 1) \cdot O(\lg n) = O(n \lg n)

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 2nlg⁡n2n \lg n, 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 2nlg⁡n2 n \lg n.

python · try it yourself
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 1.61.6 and 1.91.9 times nlg⁡nn \lg n, against lg⁡(n!)≈0.88 nlg⁡n\lg(n!) \approx 0.88\, n \lg n 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 nlg⁡nn \lg n. Heapsort is rarely the fastest sort on modern hardware, because its memory accesses jump around the array and defeat the cache, but its guaranteed O(nlg⁡n)O(n \lg n) with O(1)O(1) 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:

python · try it yourself
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 (key,original index)(key, original\ index) instead of the keys: ties are then broken by position. That costs O(n)O(n) 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?

  1. O(nlg⁡n)O(n \lg n) time, O(1)O(1) extra memory
  2. O(n2)O(n^2) time, O(1)O(1) extra memory
  3. O(nlg⁡n)O(n \lg n) time, O(n)O(n) extra memory
  4. O(n)O(n) time, O(n)O(n) extra memory

After the iteration with end=4end = 4 in heapsort on 6 values, which positions are guaranteed to hold their final values?

  1. only position 5
  2. positions 4 and 5
  3. positions 0 to 4
  4. none yet

Why does heapsort make roughly 2nlg⁡n2 n \lg n comparisons even on sorted input?

  1. Because it first reverses the input
  2. 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
  3. Because building the heap costs Θ(nlg⁡n)\Theta(n \lg n)
  4. It doesn't: sorted input costs O(n)O(n)