Computer Science · Book 3 · Bachelor Year 1

University Computer Science — Year 1

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 T(n)=2T(n/2)+nT(n) = 2T(n/2) + n and the harmonic numbers Hn=1+12+⋯+1n≈ln⁡nH_n = 1 + \frac12 + \dots + \frac1n \approx \ln n were met in Chapter 13. Heapsort sorts in place in Θ(nlog⁡n)\Theta(n \log n) (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 O(1)O(1) memory beyond the array, or O(log⁡n)O(\log n) 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 aa is a pair of positions i<ji < j with ai>aja_i > a_j.

A sorted sequence has no inversion; a reversed one has all n(n−1)/2n(n - 1)/2. 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).

Returned books go back one at a time into shelves that are already in order: insertion sort, which is fast when only a few items are out of place.
Returned books go back one at a time into shelves that are already in order: insertion sort, which is fast when only a few items are out of place.

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);
}
Listing 19.1. Lomuto’s partition and the basic quicksort code/bachelor-1/19-sorting/listings/sorts.c

Proposition 19.5 (Quicksort is correct)

qs_basic(a, lo, hi) sorts a[lo..hi)a[lo..hi) and terminates.

Proof. By strong induction on m=hi−lom = hi - lo. A slice of fewer than 2 elements is sorted. Otherwise the partition returns kk with a[lo..k)a[lo..k) smaller than a[k]a[k] and a(k..hi)a(k..hi) at least a[k]a[k] (Proposition 12.5). Both parts have fewer than mm elements, so the recursive calls sort them, and they only permute each part: the whole slice is then sorted. ∎

Quicksort of [7, 2, 9, 4, 1, 8, 5]: the first partition puts 5 (shaded) in its final place, with 2, 4, 1 on its left and 9, 8, 7 on its right; the parts are sorted in the same way. In all 6 + 2 + 1 + 2 + 1 = 12 comparisons.
Quicksort of [7,2,9,4,1,8,5][7, 2, 9, 4, 1, 8, 5]: the first partition puts 5 (shaded) in its final place, with 2, 4, 1 on its left and 9, 8, 7 on its right; the parts are sorted in the same way. In all 6+2+1+2+1=126 + 2 + 1 + 2 + 1 = 12 comparisons.

The partition of mm elements makes m−1m - 1 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 (n−1)+(n−2)+⋯+1=n(n−1)/2(n - 1) + (n - 2) + \dots + 1 = n(n - 1)/2: Θ(n2)\Theta(n^2). When the pivot always splits evenly, the recurrence C(n)=2C(n/2)+n−1C(n) = 2C(n/2) + n - 1 gives Θ(nlog⁡n)\Theta(n \log n). What happens on average?

Theorem 19.6 (Average comparisons of quicksort)

Over the n!n! orders of nn distinct keys, all equally likely, quicksort makes on average C(n)=2(n+1)Hn−4nC(n) = 2(n + 1)H_n - 4n comparisons, about 2nln⁡n≈1.39 nlog⁡2n2n \ln n \approx 1.39\, n \log_2 n.

Proof of the recurrence. The pivot is the last element; in exactly (n−1)!(n - 1)! of the n!n! orders it has rank k+1k + 1, for each k=0,…,n−1k = 0, \dots, n - 1, leaving kk smaller and n−1−kn - 1 - k 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 (n−1)!(n - 1)! orders each part comes in all its orders equally often. Hence C(0)=C(1)=0C(0) = C(1) = 0 and

C(n)=n−1+1n∑k=0n−1(C(k)+C(n−1−k))=n−1+2n∑k=0n−1C(k).C(n) = n - 1 + \frac1n \sum_{k=0}^{n-1} \bigl(C(k) + C(n - 1 - k)\bigr) = n - 1 + \frac2n \sum_{k=0}^{n-1} C(k).

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
Output 19.1. The exact average over all orders, by enumeration, against the formula, in exact fractions.

The enumeration only checks the claim for n≤8n \leq 8, and only for this program; the proof covers every nn. 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 log⁡2n\log_2 n 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
}
Listing 19.2. Quicksort with median of three, a short stack and insertion sort code/bachelor-1/19-sorting/listings/sorts.c

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);
}
Listing 19.3. Three-way quicksort code/bachelor-1/19-sorting/listings/sorts.c

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);
}
Listing 19.4. The merge, and bottom-up merge sort code/bachelor-1/19-sorting/listings/sorts.c

A merge of mm elements makes at most m−1m - 1 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 W(n)=W(⌊n/2⌋)+W(⌈n/2⌉)+n−1W(n) = W(\lfloor n/2 \rfloor) + W(\lceil n/2 \rceil) + n - 1 comparisons, which is nlog⁡2n−n+1n \log_2 n - n + 1 for n=2kn = 2^k (induction: 2(2k−1(k−1)−2k−1+1)+2k−1=k2k−2k+12(2^{k-1}(k - 1) - 2^{k-1} + 1) + 2^k - 1 = k2^k - 2^k + 1). 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 nn 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
Output 19.2. The library’s books sorted by title, then by genre: the poetry shelf.

19.4 The lower bound

Definition 19.8 (Comparison tree)

The comparison tree of a comparison sort for inputs of size nn 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.

The comparison tree of insertion sort on three keys a, b, c: six leaves, one for each order, and height 3. A sorted input takes the rightmost path, two comparisons.
The comparison tree of insertion sort on three keys a,b,ca, b, c: six leaves, one for each order, and height 3. A sorted input takes the rightmost path, two comparisons.

Theorem 19.9 (Lower bound for comparison sorts)

Every comparison sort makes at least ⌈log⁡2n!⌉\lceil \log_2 n! \rceil comparisons on some input of nn distinct keys, and log⁡2n!≥n2log⁡2n2\log_2 n! \geq \frac n2 \log_2 \frac n2: the worst case is in Ω(nlog⁡n)\Omega(n \log n).

Proof. The n!n! orders of nn distinct keys need n!n! different outputs, so the comparison tree has at least n!n! leaves. A binary tree of height hh has at most 2h2^h leaves, so 2h≥n!2^h \geq n! and h≥⌈log⁡2n!⌉h \geq \lceil \log_2 n! \rceil. Finally, n!n! has at least n/2n/2 factors at least n/2n/2, so n!≥(n/2)n/2n! \geq (n/2)^{n/2}. ∎

$ 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
Output 19.3. The bound ⌈log⁡2n!⌉\lceil \log_2 n! \rceil against the worst cases of three sorts.

Merge sort stays within about 10 % of the bound; merge insertion, the method of the problem, meets it exactly up to n=11n = 11, then is off by one. The same argument bounds the average: a binary tree with NN leaves has an average leaf depth at least log⁡2N\log_2 N, so even on average a comparison sort makes at least log⁡2n!\log_2 n! comparisons. Quicksort’s 1.39 nlog⁡2n1.39\, n \log_2 n is, for large nn, 39 % above it.

Comparisons from , averaged over 200 random orders. Quicksort on sorted input leaves the chart at n = 36 (630 comparisons). Merge sort hugs the bound; heapsort makes about twice as many.
Comparisons from Output 19.4, averaged over 200 random orders. Quicksort on sorted input leaves the chart at n=36n = 36 (630 comparisons). Merge sort hugs the bound; heapsort makes about twice as many.
$ 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
Output 19.4. Comparisons of the sorts of Listings 19.1, 19.2 and 19.4 and of heapsort; 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 nn keys in {0,…,k−1}\{0, \dots, k - 1\} 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 dd digits by dd 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
}
Listing 19.5. Counting sort on one decimal digit code/bachelor-1/19-sorting/listings/radix.c

Counting sort costs Θ(n+k)\Theta(n + k) and is stable, since keys are copied in input order into their block. Radix sort costs Θ(d(n+k))\Theta(d(n + k)): linear in nn 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
Output 19.5. Radix sort of seven 3-digit keys, one pass per digit.
The passes of . The arrows follow 457 and 355 into the pass on the tens: equal digits, so the stable pass leaves them in the order the units gave them.
The passes of Output 19.5. The arrows follow 457 and 355 into the pass on the tens: equal digits, so the stable pass leaves them in the order the units gave them.

Proposition 19.11 (Radix sort is correct)

After the pass on digit jj (counting from 1 at the units), the keys are sorted by their last jj digits.

The proof, by induction on jj, 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
Output 19.6. Radix sort of the loans’ return dates.

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.

An IBM 82 card sorter at the Computer History Museum. The row of pockets along the front received the cards, one pocket per row of the card. Photograph: leighklotz, CC BY 2.0.
An IBM 82 card sorter at the Computer History Museum. The row of pockets along the front received the cards, one pocket per row of the card. Photograph: leighklotz, CC BY 2.0.

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 log⁡n\log n; small parts are left to insertion sort.

Introsort keeps quicksort’s speed on ordinary input and heapsort’s O(nlog⁡n)O(n \log n) guarantee on inputs that defeat the pivot choice. The C++ standard requires of std::sort O(nlog⁡n)O(n \log n) 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 2⌊log⁡2n⌋2\lfloor \log_2 n \rfloor, 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
Output 19.7. Sorting a million random integers, measured on the author’s laptop.

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 [3,8,2,5,1,4,7,6][3, 8, 2, 5, 1, 4, 7, 6]. Give the array and the pivot’s index.

Solution

Solution of Exercise 19.1.

The pivot is 6. The keys 3, 2, 5, 1, 4 are smaller and are moved, in this order, to the front; 8 and 7 are not. The final exchange puts 6 after them: [3,2,5,1,4,6,7,8][3, 2, 5, 1, 4, 6, 7, 8], pivot at index 5, after 7 comparisons.

Exercise 19.2 ★

Merge [1,4,7,9][1, 4, 7, 9] and [2,3,8,10,11][2, 3, 8, 10, 11], 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: [1,2,3,4,7,8,9,10,11][1, 2, 3, 4, 7, 8, 9, 10, 11] in 7 comparisons.

Exercise 19.3 ★

Counting sort is applied to [3,1,4,1,5,2,0,3][3, 1, 4, 1, 5, 2, 0, 3] with k=6k = 6. Give the count array, the block starts and the output.

Solution

Solution of Exercise 19.3.

Counts for 0 to 5: 1,2,1,2,1,11, 2, 1, 2, 1, 1. Block starts: 0,1,3,4,6,70, 1, 3, 4, 6, 7. Output: [0,1,1,2,3,3,4,5][0, 1, 1, 2, 3, 3, 4, 5], the two 1s and the two 3s in their input order.

Exercise 19.4 ★

The records (2,a),(1,b),(2,c),(1,d)(2, \mathrm{a}), (1, \mathrm{b}), (2, \mathrm{c}), (1, \mathrm{d}) 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 (1,b),(1,d),(2,a),(2,c)(1, \mathrm{b}), (1, \mathrm{d}), (2, \mathrm{a}), (2, \mathrm{c}). Selection sort is not stable: on (2,a),(2,c),(1,b)(2, \mathrm{a}), (2, \mathrm{c}), (1, \mathrm{b}), the first exchange moves (2,a)(2, \mathrm{a}) behind (2,c)(2, \mathrm{c}), and the output is (1,b),(2,c),(2,a)(1, \mathrm{b}), (2, \mathrm{c}), (2, \mathrm{a}).

Exercise 19.5 ★★

Explain the counts of the basic quicksort on nn equal keys, and why the three-way version makes 2n2n 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
Output 19.8. Equal keys. Some lines are left out.
Solution

Solution of Exercise 19.5.

With all keys equal, no key is smaller than the pivot: the partition makes m−1m - 1 comparisons, leaves the left part empty and the right part with m−1m - 1 keys. In all (n−1)+⋯+1=n(n−1)/2(n - 1) + \dots + 1 = n(n - 1)/2, which is 499 500 for n=1000n = 1000. 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: 2n2n.

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];
}
Listing 19.6. Filling the blocks backwards code/bachelor-1/19-sorting/listings/exo_radix_bug.c
355 329 457 436 657 720 839
Output 19.9. Radix sort of the keys of Output 19.5. Some lines are left out.
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 aj>aj+1a_j > a_{j+1} 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 ⌈log⁡212!⌉\lceil \log_2 12! \rceil. 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.

12!=479 001 60012! = 479\,001\,600 and log⁡212!≈28.84\log_2 12! \approx 28.84: 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 nn, subtract the equation for n−1n - 1, divide by n(n+1)n(n + 1), and sum.

Solution

Solution of Exercise 19.10.

Multiplying by nn: nC(n)=n(n−1)+2∑k<nC(k)nC(n) = n(n - 1) + 2\sum_{k<n} C(k); the same for n−1n - 1, subtracted: nC(n)−(n−1)C(n−1)=2(n−1)+2C(n−1)nC(n) - (n - 1)C(n - 1) = 2(n - 1) + 2C(n - 1), so nC(n)=(n+1)C(n−1)+2(n−1)nC(n) = (n + 1)C(n - 1) + 2(n - 1). Dividing by n(n+1)n(n + 1) and using 2(n−1)n(n+1)=4n+1−2n\frac{2(n - 1)}{n(n + 1)} = \frac{4}{n + 1} - \frac2n:

C(n)n+1=C(n−1)n+4n+1−2n=∑j=2n(4j+1−2j)=2Hn+4n+1−4,\frac{C(n)}{n + 1} = \frac{C(n - 1)}{n} + \frac{4}{n + 1} - \frac2n = \sum_{j=2}^{n} \Bigl(\frac{4}{j + 1} - \frac2j\Bigr) = 2H_n + \frac{4}{n + 1} - 4,

since C(1)=0C(1) = 0. Hence C(n)=2(n+1)Hn−4nC(n) = 2(n + 1)H_n - 4n; with Hn≈ln⁡nH_n \approx \ln n, C(n)≈2nln⁡nC(n) \approx 2n \ln n.

Exercise 19.11 ★★★

Count the inversions of an array in O(nlog⁡n)O(n \log n) 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;
}
Counting inversions while merging code/bachelor-1/19-sorting/exercises/inversions.c

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 a[j]a[j] from the right half while h−ih - i keys remain in the left half, each of them is larger than a[j]a[j] and before it: h−ih - i inversions of the third kind, each counted once. The cost is that of merge sort, O(nlog⁡n)O(n \log n); the test compares with the double loop for n≤300n \leq 300 on six kinds of input.

Exercise 19.12 ★★★

Prove Proposition 19.11 by induction on jj.

Solution

Solution of Exercise 19.12.

For j=0j = 0 there is nothing to prove. Suppose the keys sorted by their last jj digits before the pass on digit j+1j + 1. Take two keys xx and yy. If their digits j+1j + 1 differ, the pass orders them by that digit, which decides the order of their last j+1j + 1 digits. If they are equal, the pass, being stable, leaves xx and yy in their previous order, the order of their last jj digits, which is then the order of their last j+1j + 1 digits. So after the pass the keys are sorted by their last j+1j + 1 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
Listing 19.7. Merge insertion for five keys code/bachelor-1/19-sorting/listings/sort5.py
$ 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}
Output 19.10. All 120 orders, for three methods.

Part I — The lower bound.

  1. Compute ⌈log⁡2120⌉\lceil \log_2 120 \rceil, and conclude that no comparison sort sorts every order of five keys in six comparisons.
  2. Why is the bound about the worst case, and what does the average bound log⁡2120\log_2 120 say?
  3. 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?
  4. 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 dd to the 27−d2^{7 - d} positions below it at depth 7.) How many does merge insertion have?
  5. After the first three comparisons of merge insertion, how many of the 120 orders are still possible? Why can at most 242^4 remain after three comparisons of any method that always finishes in seven?
  6. For n=4n = 4, compute the bound, and find a method meeting it.

Part II — Two familiar methods.

  1. Which input makes insertion sort take 10 comparisons on five keys, and which 4?
  2. Explain insertion sort’s average, 7.72, from the inversions.
  3. Compute merge sort’s worst case on five keys from the recurrence W(n)W(n).
  4. Find an order of five keys on which merge sort makes 8 comparisons.
  5. Why does merge sort never take fewer than 5 comparisons on five keys?
  6. Which of the two methods is closer to the bound?

Part III — Merge insertion.

  1. After the first three comparisons, what is known about a,b,c,da, b, c, d?
  2. Why does inserting ee into the chain a<b<da < b < d cost at most 2 comparisons?
  3. Why does cc need to be compared only with the elements below dd, and why are there at most three of them?
  4. Count the comparisons of the method in the worst case.
  5. Trace the method on the order (4,1,3,0,2)(4, 1, 3, 0, 2) of the keys 0,…,40, \dots, 4 assigned to a,…,ea, \dots, e.
  6. Why does inserting ee before cc give a better worst case than inserting cc first?

Part IV — Checking every order.

  1. What does the program check on each of the 120 orders?
  2. Why is checking all 120 orders a proof for five distinct keys, and why are distinct keys enough?
  3. How many orders take only 6 comparisons? Is that compatible with the lower bound?
  4. The general method sorts nn keys in ∑k=1n⌈log⁡23k4⌉\sum_{k=1}^{n} \lceil \log_2 \frac{3k}{4} \rceil comparisons. Check this for n=5n = 5 and compare with the bound for n=12n = 12.
  5. Why is an exhaustive check impossible for n=20n = 20?
  6. 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. 26=64<120≤128=272^6 = 64 < 120 \leq 128 = 2^7: ⌈log⁡2120⌉=7\lceil \log_2 120 \rceil = 7. 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 log⁡2120≈6.91\log_2 120 \approx 6.91; merge insertion’s mean, 6.93, is almost there.

3. At least 120 leaves; at most 27=1282^7 = 128.

4. A leaf at depth d≤6d \leq 6 takes at least 2 of the 128 positions at depth 7, a leaf at depth 7 one: 2x+(120−x)≤1282x + (120 - x) \leq 128, so x≤8x \leq 8. Merge insertion has exactly 8 orders sorted in 6 comparisons.

5. a<b<da < b < d and c<dc < d leave 3 orders of a,b,c,da, b, c, d (cc before aa, between aa and bb, or between bb and dd), and ee 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. ⌈log⁡224⌉=5\lceil \log_2 24 \rceil = 5. Merge sort sorts 4 keys in at most 1+1+3=51 + 1 + 3 = 5 comparisons.

7. 10 on the reversed order (4,3,2,1,0)(4, 3, 2, 1, 0), 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 n(n−1)/4=5n(n - 1)/4 = 5 inversions, and the element at position ii reaches the front with probability 1/(i+1)1/(i + 1): 5+4−(12+13+14+15)≈7.725 + 4 - (\frac12 + \frac13 + \frac14 + \frac15) \approx 7.72.

9. W(1)=0W(1) = 0, W(2)=1W(2) = 1, W(3)=W(1)+W(2)+2=3W(3) = W(1) + W(2) + 2 = 3, W(5)=W(2)+W(3)+4=8W(5) = W(2) + W(3) + 4 = 8.

10. The order (0,3,2,1,4)(0, 3, 2, 1, 4) (found by the program): every merge runs to its last element.

11. Each merge of pp and qq elements makes at least min⁡(p,q)\min(p, q) comparisons: 1+(1+1)+2=51 + (1 + 1) + 2 = 5.

12. Merge sort: 8 against 10, one above the bound.

13. a<b<da < b < d and c<dc < d; nothing about ee.

14. Binary search in a chain of 3 has 4 possible places, and ⌈log⁡24⌉=2\lceil \log_2 4 \rceil = 2.

15. c<dc < d, so its place is among the keys below dd: aa, bb, and ee if e<de < d. Three keys give 4 places, 2 comparisons.

16. 3+2+2=73 + 2 + 2 = 7.

17. a,b,c,d,e=4,1,3,0,2a, b, c, d, e = 4, 1, 3, 0, 2. Comparison 1 exchanges aa and bb (a=1a = 1, b=4b = 4); comparison 2 exchanges cc and dd (c=0c = 0, d=3d = 3); comparison 3, 3<43 < 4, exchanges the pairs: a,b,c,d=0,3,1,4a, b, c, d = 0, 3, 1, 4. The chain 0<3<40 < 3 < 4; e=2e = 2 is compared with 3, then 0: chain 0,2,3,40, 2, 3, 4. Then c=1c = 1, below 4, is compared with 2, then 0: 0,1,2,3,40, 1, 2, 3, 4, in 7 comparisons.

18. Inserting cc first costs 2 comparisons (among aa, bb), but leaves a chain of 4 for ee, with 5 places: 3 comparisons, 8 in all. Inserting ee 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 k=1,…,5k = 1, \dots, 5 are 0,1,2,2,20, 1, 2, 2, 2: 7. For 12 keys the method needs 30, one more than the bound 29.

23. 20!≈2.4×101820! \approx 2.4 \times 10^{18} 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).

Terms defined in this chapter

See all 1050 terms in the glossary