University Computer Science — Year 1 · Bachelor Year 1
19Sorting
Before electronic computers, a population census was sorted by machines that read punched cards. A card carried one person’s answers as holes in columns; the sorting machine read one column and dropped each card into the pocket of the digit punched there. To sort by a three-digit code, the operator ran the deck through the machine three times, starting with the last digit, stacking the pockets in order after each pass. It looks backwards, and it works: this chapter proves why. It also builds the comparison sorts used today, quicksort and merge sort, counts their comparisons exactly or on average, and proves that no sort that only compares keys can do much better.
You already know
Lomuto’s partition rearranges a slice around a pivot, with a proved invariant (Proposition 12.5). Recurrences such as and the harmonic numbers were met in Chapter 13. Heapsort sorts in place in (Method 18.7). Insertion sort inserts each element into the sorted prefix before it.
19.1 What a sort promises
Definition 19.1 (Comparison sort, in-place sort)
A comparison sort learns about the keys only by comparing two of them. A sort is in place when it uses memory beyond the array, or for a recursion stack.
Definition 19.2 (Stable sort)
A sort is stable when elements with equal keys keep, in the output, the order they had in the input.
Stability matters for records sorted by one field after another: sorting books by title, then stably by genre, gives each genre’s books in alphabetical order.
Definition 19.3 (Inversion)
An inversion of a sequence is a pair of positions with .
A sorted sequence has no inversion; a reversed one has all . Each exchange of two neighbours removes exactly one inversion, which is why insertion sort, which only exchanges neighbours, costs as many exchanges as the input has inversions (Exercise 19.8).
19.2 Quicksort
Definition 19.4 (Quicksort, pivot, three-way partition)
Quicksort chooses an element, the pivot, partitions the array into the elements smaller than the pivot, the pivot, and the others, and sorts the two parts recursively. A three-way partition separates the elements smaller than, equal to and larger than the pivot.
static int partition(int *a, int lo, int hi) { // a[lo..hi), pivot a[hi - 1]; as in chapter 12
int p = a[hi - 1], k = lo;
for (int j = lo; j < hi - 1; j++)
if (less(a[j], p)) swap(a, k++, j); // invariant: a[lo..k) < p <= a[k..j)
swap(a, k, hi - 1);
return k;
}
static void qs_basic(int *a, int lo, int hi) {
if (hi - lo < 2) return;
int k = partition(a, lo, hi); // a[lo..k) < a[k] <= a(k..hi)
qs_basic(a, lo, k);
qs_basic(a, k + 1, hi);
}
Proposition 19.5 (Quicksort is correct)
qs_basic(a, lo, hi) sorts and terminates.
Proof. By strong induction on . A slice of fewer than 2 elements is sorted. Otherwise the partition returns with smaller than and at least (Proposition 12.5). Both parts have fewer than elements, so the recursive calls sort them, and they only permute each part: the whole slice is then sorted. ∎
The partition of elements makes comparisons. When the pivot is always the largest element, as on a sorted array with the last element as pivot, one part is empty, and the total is : . When the pivot always splits evenly, the recurrence gives . What happens on average?
Theorem 19.6 (Average comparisons of quicksort)
Over the orders of distinct keys, all equally likely, quicksort makes on average comparisons, about .
Proof of the recurrence. The pivot is the last element; in exactly of the orders it has rank , for each , leaving smaller and larger elements. Lomuto’s partition keeps the relative order of the smaller elements, and of the larger ones up to a fixed rearrangement, so over these orders each part comes in all its orders equally often. Hence and
Exercise 19.10 solves it. ∎
$ python qs_average.py
n n! average 2(n+1)H_n - 4n worst
1 1 0 0 0
2 2 1 1 1
3 6 8/3 8/3 3
4 24 29/6 29/6 6
5 120 37/5 37/5 10
6 720 103/10 103/10 15
7 5040 472/35 472/35 21
8 40320 2369/140 2369/140 28
The enumeration only checks the claim for , and only for this program; the proof covers every . The fair-order assumption is the weak point: input is often sorted, or nearly. Three changes make quicksort robust. The pivot is the median of the first, middle and last elements, which is good on sorted input. The recursion goes into the smaller part and a loop handles the larger one, so the stack holds at most frames, since each frame’s part is at most half the previous one. Parts of 16 elements or fewer are left to insertion sort, which is faster on small arrays.
static void qs(int *a, int lo, int hi) {
while (hi - lo > 16) {
int mid = lo + (hi - lo) / 2; // median of three to the pivot position hi - 1
if (less(a[mid], a[lo])) swap(a, mid, lo);
if (less(a[hi - 1], a[lo])) swap(a, hi - 1, lo);
if (less(a[mid], a[hi - 1])) swap(a, mid, hi - 1);
int k = partition(a, lo, hi);
if (k - lo < hi - k) qs(a, lo, k), lo = k + 1; // recurse on the smaller side,
else qs(a, k + 1, hi), hi = k; // loop on the larger one
}
insertion_sort(a + lo, hi - lo); // small parts
}
Equal keys remain a trap: with all keys equal, Lomuto’s partition puts every element on one side (Exercise 19.5). The three-way partition puts them in the middle, which is left out of the recursion.
static void qs3(int *a, int lo, int hi) {
if (hi - lo < 2) return;
int p = a[lo + (hi - lo) / 2], lt = lo, i = lo, gt = hi;
while (i < gt) // invariant: a[lo..lt) < p, a[lt..i) == p, a[gt..hi) > p
if (less(a[i], p)) swap(a, lt++, i++);
else if (less(p, a[i])) swap(a, i, --gt);
else i++;
qs3(a, lo, lt);
qs3(a, gt, hi);
}
19.3 Merge sort
Definition 19.7 (Merge, merge sort)
To merge two sorted sequences is to build the sorted sequence of their elements by repeatedly taking the smaller of their two first elements. Merge sort sorts the two halves of an array recursively and merges them.
static void merge(int *a, int lo, int mid, int hi, int *tmp) { // a[lo..mid), a[mid..hi) sorted
memcpy(tmp + lo, a + lo, (size_t)(hi - lo) * sizeof *a);
int i = lo, j = mid;
for (int k = lo; k < hi; k++)
if (i < mid && (j == hi || !less(tmp[j], tmp[i]))) a[k] = tmp[i++]; // ties: left first
else a[k] = tmp[j++];
}
void merge_sort_bottom_up(int *a, int n) { // runs of width 1, 2, 4, ... merged in pairs
int *tmp = malloc((size_t)n * sizeof *tmp + 1);
if (tmp == NULL) exit(1);
for (int w = 1; w < n; w *= 2)
for (int lo = 0; lo + w < n; lo += 2 * w)
merge(a, lo, lo + w, lo + 2 * w < n ? lo + 2 * w : n, tmp);
free(tmp);
}
A merge of elements makes at most comparisons. The top-down version splits recursively; the bottom-up version merges runs of width 1, then 2, 4, and so on, with no recursion. Both make at most comparisons, which is for (induction: ). On a tie the merge takes the element of the left run first, which makes merge sort stable. Its price is an extra array of elements.
$ gcc -std=c17 -O2 -Wall -Wextra -o stable stable.c -lm && ./stable
merge sort (stable):
A Map of the Lighthouse
A Year by the Lighthouse
The Clockwork Code
The Hidden Machine
The Last Lighthouse
The Lost Code
The Silent Machine
The Silent Valley
heapsort (not stable):
The Lost Code
The Last Lighthouse
The Hidden Machine
The Silent Valley
A Year by the Lighthouse
The Silent Machine
A Map of the Lighthouse
The Clockwork Code
19.4 The lower bound
Definition 19.8 (Comparison tree)
The comparison tree of a comparison sort for inputs of size is the binary tree whose internal nodes are the comparisons the sort makes, with one subtree for each outcome, and whose leaves are the outputs. An input follows one path from the root to a leaf; the length of the path is the number of comparisons.
Theorem 19.9 (Lower bound for comparison sorts)
Every comparison sort makes at least comparisons on some input of distinct keys, and : the worst case is in .
Proof. The orders of distinct keys need different outputs, so the comparison tree has at least leaves. A binary tree of height has at most leaves, so and . Finally, has at least factors at least , so . ∎
$ python lower_bound.py
n lg n! bound insertion merge merge insertion
2 1.00 1 1 1 1
3 2.58 3 3 3 3
4 4.58 5 6 5 5
5 6.91 7 10 8 7
6 9.49 10 15 11 10
7 12.30 13 21 14 13
8 15.30 16 28 17 16
9 18.47 19 36 21 19
10 21.79 22 45 25 22
11 25.25 26 55 29 26
12 28.84 29 66 33 30
13 32.54 33 78 37 34
14 36.34 37 91 41 38
15 40.25 41 105 45 42
16 44.25 45 120 49 46
Merge sort stays within about 10 % of the bound; merge insertion, the method of the problem, meets it exactly up to , then is off by one. The same argument bounds the average: a binary tree with leaves has an average leaf depth at least , so even on average a comparison sort makes at least comparisons. Quicksort’s is, for large , 39 % above it.
$ gcc -std=c17 -O2 -Wall -Wextra -o counts counts.c sorts.c -lm && ./counts
n qs sorted qs random qs+ merge heap bound
4 6 4.9 4.8 4.7 6.5 5
8 28 16.7 19.3 15.8 25.8 16
12 66 32.5 42.9 30.1 51.8 29
16 120 50.6 72.1 45.7 80.5 45
20 190 71.6 83.3 63.4 114.3 62
24 276 91.8 107.1 81.8 149.5 80
28 378 115.9 131.7 101.5 185.4 98
32 496 141.0 156.4 121.4 223.0 118
36 630 164.7 187.8 143.1 264.0 139
40 780 190.9 211.7 165.2 306.1 160
44 946 218.3 238.4 187.5 348.5 181
48 1128 244.2 266.6 210.5 392.4 203
52 1326 271.8 297.0 233.4 436.7 226
56 1540 302.3 324.6 257.4 481.5 249
60 1770 331.3 357.0 281.4 525.3 273
64 2016 359.5 387.6 305.0 571.6 296
qs+ is Listing 19.2.19.5 Sorting without comparisons
The lower bound holds only for algorithms that compare keys. Keys that are small integers, or strings of digits, can be sorted by looking at their digits.
Definition 19.10 (Counting sort, radix sort)
Counting sort sorts keys in by counting the keys of each value, computing from the counts where each value’s block starts, and copying each key to the next free cell of its block, in input order. Radix sort, least significant digit first, sorts keys of digits by passes of a stable sort on one digit, from the last digit to the first.
void counting_sort_digit(const int *in, int *out, int n, int place) {
int count[10] = {0};
for (int i = 0; i < n; i++) count[in[i] / place % 10]++;
int start[10]; // start[d]: the first output cell of the keys with digit d
for (int d = 0, sum = 0; d < 10; d++) start[d] = sum, sum += count[d];
for (int i = 0; i < n; i++) out[start[in[i] / place % 10]++] = in[i]; // in input order
}
Counting sort costs and is stable, since keys are copied in input order into their block. Radix sort costs : linear in for keys of a fixed number of digits.
$ gcc -std=c17 -O2 -Wall -Wextra -o radix_demo radix_demo.c radix.c -lm && ./radix_demo
input 329 457 657 839 436 720 355
by units 720 355 436 457 657 329 839
by tens 720 329 436 839 355 457 657
by hundreds 329 355 436 457 657 720 839
Proposition 19.11 (Radix sort is correct)
After the pass on digit (counting from 1 at the units), the keys are sorted by their last digits.
The proof, by induction on , rests on the stability of each pass (Exercise 19.12); with an unstable pass, it fails (Exercise 19.6). The punched-card machines used exactly this method, one column per pass. The returns of the town’s loans, as eight-digit numbers yyyymmdd, sort in eight passes:
$ gcc -std=c17 -O2 -Wall -Wextra -o radix_loans radix_loans.c radix.c -lm && ./radix_loans
378 returns; first 20250103, 20250108, 20250109; last 20260111; same as qsort: yes
History — Card sorters
The machines of this chapter’s opening were built for decades. IBM’s type 82 sorter of 1949 read one column of each card with a metal brush and dropped the card into one of 13 pockets, one for each of the 12 rows a hole could be punched in and one for blank or rejected cards, at 650 cards a minute. A deck was sorted on a key of several columns one column at a time, least significant first, the operator collecting the pockets in order between passes: a radix sort, run by hand.
19.6 How library sorts are built
Definition 19.12 (Introsort)
Introsort is a quicksort that counts its recursion depth and switches to heapsort on a part once the depth passes a limit proportional to ; small parts are left to insertion sort.
Introsort keeps quicksort’s speed on ordinary input and heapsort’s guarantee on inputs that defeat the pivot choice. The C++ standard requires of std::sort comparisons in the worst case, and allows it to be unstable; std::stable_sort is the stable one.
Facts as of 2026
The GNU C++ library implements std::sort as an introsort: a depth limit of , a heap-based sort when it runs out, parts of up to 16 elements left for a final insertion sort. CPython sorts lists with timsort, a stable, adaptive merge sort that finds the runs already sorted in the input and merges them; its merge order now follows the powersort strategy. Both are read from the libraries’ source code; such details change between versions.
$ gcc -std=c17 -O2 -Wall -Wextra -o timing timing.c sorts.c radix.c -lm && ./timing
qsort (C library) 96.0 ms
quicksort 53.5 ms
merge sort 82.3 ms
heapsort 91.5 ms
radix sort 28.6 ms
The C library’s qsort calls a comparison function through a pointer for every comparison, which the sorts of this chapter avoid; radix sort, with nine passes over the data and no comparison, is the fastest here. Measured times depend on the machine and the compiler, and say nothing about the worst case.
19.7 Exercises
Exercise 19.1 ★
Apply Lomuto’s partition, with the last element as pivot, to . Give the array and the pivot’s index.
Exercise 19.2 ★
Merge and , and count the comparisons.
Solution
Solution of Exercise 19.2.
1 (1 against 2), 2 (4 against 2), 3 (4 against 3), 4 (4 against 8), 7 (7 against 8), 8 (9 against 8), 9 (9 against 10); the first list is then empty and 10, 11 are copied: in 7 comparisons.
Exercise 19.3 ★
Counting sort is applied to with . Give the count array, the block starts and the output.
Solution
Solution of Exercise 19.3.
Counts for 0 to 5: . Block starts: . Output: , the two 1s and the two 3s in their input order.
Exercise 19.4 ★
The records are sorted by their number. Which outputs are those of a stable sort? Is selection sort, which exchanges the minimum of the rest with the current element, stable?
Solution
Solution of Exercise 19.4.
Only . Selection sort is not stable: on , the first exchange moves behind , and the output is .
Exercise 19.5 ★★
Explain the counts of the basic quicksort on equal keys, and why the three-way version makes comparisons.
n = 1000: basic 499500 comparisons, three-way 2000
n = 2000: basic 1999000 comparisons, three-way 4000
n = 4000: basic 7998000 comparisons, three-way 8000
Solution
Solution of Exercise 19.5.
With all keys equal, no key is smaller than the pivot: the partition makes comparisons, leaves the left part empty and the right part with keys. In all , which is 499 500 for . The three-way partition compares each key twice (not smaller, not larger), puts all of them in the middle, and recurses on two empty parts: .
Exercise 19.6 ★★
This counting sort fills each digit’s block from its end. Show that it sorts by one digit correctly, explain the output of a radix sort built on it, and repair it.
void digit_sort(const int *in, int *out, int n, int place) {
int end[10] = {0};
for (int i = 0; i < n; i++) end[in[i] / place % 10]++;
for (int d = 1; d < 10; d++) end[d] += end[d - 1]; // end[d]: one past the block of d
for (int i = 0; i < n; i++) out[--end[in[i] / place % 10]] = in[i];
}
355 329 457 436 657 720 839
Solution
Solution of Exercise 19.6.
Each key goes to the last free cell of its digit’s block, so the blocks are in digit order: one pass sorts by its digit. But within a block the keys come out in the reverse of their input order: the sort is not stable. The last pass, on the hundreds, reverses 329 and 355, which the pass on the tens had put in order; the result is wrong. The repair walks the input from its end, for (int i = n - 1; i >= 0; i--), so that the last key of each digit takes the last cell.
Exercise 19.7 ★★
Sort the town’s loans by member, and by date within each member, with a stable sort applied twice. In which order must the two sorts be applied? Test the result against a sort on the pair.
Solution
Solution of Exercise 19.7.
Sort by date first, then by member, with a stable sort: the second sort orders by member, and stability keeps the date order inside each member (exercises/loans_by_member.py). In the other order the dates would be the primary key. The test compares the result with a sort on the pair (member, date).
Exercise 19.8 ★★
Prove that insertion sort makes exactly as many exchanges as its input has inversions.
Solution
Solution of Exercise 19.8.
Exchanging two neighbours removes the inversion they form and changes no other pair’s relative order: the number of inversions drops by exactly 1. Insertion sort exchanges only such neighbours, and stops with a sorted array, which has no inversion. So it makes exactly as many exchanges as there were inversions.
Exercise 19.9 ★★
Compute . What does it say about sorting 12 keys? Compare with merge sort and merge insertion in Output 19.3.
Solution
Solution of Exercise 19.9.
and : every comparison sort needs at least 29 comparisons for some order of 12 keys. Merge sort needs 33 in its worst case, merge insertion 30. The bound does not say whether 29 can be reached.
Exercise 19.10 ★★★
Solve the recurrence of Theorem 19.6: multiply by , subtract the equation for , divide by , and sum.
Solution
Solution of Exercise 19.10.
Multiplying by : ; the same for , subtracted: , so . Dividing by and using :
since . Hence ; with , .
Exercise 19.11 ★★★
Count the inversions of an array in by modifying merge sort, and test against the quadratic count.
Solution
Solution of Exercise 19.11.
static long count(int *a, int n, int *tmp) {
if (n < 2) return 0;
int h = n / 2, i = 0, j = h;
long inv = count(a, h, tmp) + count(a + h, n - h, tmp);
for (int k = 0; k < n; k++)
if (i < h && (j == n || a[i] <= a[j])) tmp[k] = a[i++];
else inv += h - i, tmp[k] = a[j++]; // a[j] < the h - i keys left
memcpy(a, tmp, (size_t)n * sizeof *a);
return inv;
}
An inversion has both ends in the left half, both in the right half, or one in each; the recursive calls count the first two kinds. When the merge takes from the right half while keys remain in the left half, each of them is larger than and before it: inversions of the third kind, each counted once. The cost is that of merge sort, ; the test compares with the double loop for on six kinds of input.
Exercise 19.12 ★★★
Prove Proposition 19.11 by induction on .
Solution
Solution of Exercise 19.12.
For there is nothing to prove. Suppose the keys sorted by their last digits before the pass on digit . Take two keys and . If their digits differ, the pass orders them by that digit, which decides the order of their last digits. If they are equal, the pass, being stable, leaves and in their previous order, the order of their last digits, which is then the order of their last digits. So after the pass the keys are sorted by their last digits.
19.8 Problem: Five keys in seven comparisons
Problem 19.1
Weekend problem — Five keys in seven comparisons
How few comparisons can sort five keys? A program sorts all 120 orders of five keys with insertion sort, merge sort and merge insertion, counting the comparisons with a key type that counts them.
def merge_insertion5(a, b, c, d, e):
if b < a: # 1: order the pair (a, b)
a, b = b, a
if d < c: # 2: order the pair (c, d)
c, d = d, c
if d < b: # 3: order the pairs by their larger keys: a < b < d and c < d
a, b, c, d = c, d, a, b
chain = [a, b, d]
insert(chain, e, 3) # 4, 5: e into a chain of three
insert(chain, c, chain.index(d)) # 6, 7: c among the keys below d, at most three
return chain
$ python sort5.py
insertion sort worst 10, mean 7.72, counts {4: 2, 5: 8, 6: 16, 7: 26, 8: 28, 9: 24, 10: 16}
merge sort worst 8, mean 7.17, counts {5: 4, 6: 20, 7: 48, 8: 48}
merge insertion worst 7, mean 6.93, counts {6: 8, 7: 112}
Part I — The lower bound.
- Compute , and conclude that no comparison sort sorts every order of five keys in six comparisons.
- Why is the bound about the worst case, and what does the average bound say?
- How many leaves at least has the comparison tree of a sort of five keys, and how many leaves at most has a tree of height 7?
- Show that a comparison tree of height 7 with 120 leaves has at most 8 leaves at depth 6 or less. (Extend each leaf at depth to the positions below it at depth 7.) How many does merge insertion have?
- After the first three comparisons of merge insertion, how many of the 120 orders are still possible? Why can at most remain after three comparisons of any method that always finishes in seven?
- For , compute the bound, and find a method meeting it.
Part II — Two familiar methods.
- Which input makes insertion sort take 10 comparisons on five keys, and which 4?
- Explain insertion sort’s average, 7.72, from the inversions.
- Compute merge sort’s worst case on five keys from the recurrence .
- Find an order of five keys on which merge sort makes 8 comparisons.
- Why does merge sort never take fewer than 5 comparisons on five keys?
- Which of the two methods is closer to the bound?
Part III — Merge insertion.
- After the first three comparisons, what is known about ?
- Why does inserting into the chain cost at most 2 comparisons?
- Why does need to be compared only with the elements below , and why are there at most three of them?
- Count the comparisons of the method in the worst case.
- Trace the method on the order of the keys assigned to .
- Why does inserting before give a better worst case than inserting first?
Part IV — Checking every order.
- What does the program check on each of the 120 orders?
- Why is checking all 120 orders a proof for five distinct keys, and why are distinct keys enough?
- How many orders take only 6 comparisons? Is that compatible with the lower bound?
- The general method sorts keys in comparisons. Check this for and compare with the bound for .
- Why is an exhaustive check impossible for ?
- State the named result: five keys can be sorted in seven comparisons, and no method does it in six.
Solution
Solution of Problem 19.1.
1. : . A tree of height 6 has at most 64 leaves, fewer than the 120 orders.
2. The height of the tree is the worst case. The average depth of 120 leaves is at least ; merge insertion’s mean, 6.93, is almost there.
3. At least 120 leaves; at most .
4. A leaf at depth takes at least 2 of the 128 positions at depth 7, a leaf at depth 7 one: , so . Merge insertion has exactly 8 orders sorted in 6 comparisons.
5. and leave 3 orders of ( before , between and , or between and ), and can be in any of 5 places: 15 orders. After three comparisons, the leaves still reachable must fit in a subtree of height 4, which has at most 16 leaves.
6. . Merge sort sorts 4 keys in at most comparisons.
7. 10 on the reversed order , which has 10 inversions; 4 on the sorted order.
8. Insertion sort makes one comparison per exchange, plus one per element that stops before reaching the front. On average there are inversions, and the element at position reaches the front with probability : .
9. , , , .
10. The order (found by the program): every merge runs to its last element.
11. Each merge of and elements makes at least comparisons: .
12. Merge sort: 8 against 10, one above the bound.
13. and ; nothing about .
14. Binary search in a chain of 3 has 4 possible places, and .
15. , so its place is among the keys below : , , and if . Three keys give 4 places, 2 comparisons.
16. .
17. . Comparison 1 exchanges and (, ); comparison 2 exchanges and (, ); comparison 3, , exchanges the pairs: . The chain ; is compared with 3, then 0: chain . Then , below 4, is compared with 2, then 0: , in 7 comparisons.
18. Inserting first costs 2 comparisons (among , ), but leaves a chain of 4 for , with 5 places: 3 comparisons, 8 in all. Inserting first keeps both insertions at 4 places.
19. That the result is sorted, and how many comparisons it took.
20. A comparison sort’s behaviour depends only on the outcomes of its comparisons, that is on the relative order of the keys; 120 orders are all the relative orders of five distinct keys.
21. 8 orders. Yes: the bound is on the worst case, and question 4 allows up to 8.
22. The terms for are : 7. For 12 keys the method needs 30, one more than the bound 29.
23. orders, far too many to enumerate.
24. Five keys can be sorted in seven comparisons, and no method does it in six: six comparisons distinguish at most 64 outcomes, fewer than the 120 orders (question 1); merge insertion sorts every one of the 120 orders in at most seven, as the exhaustive check confirms (Output 19.10).