---
title: "Sorting"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 19
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/19-sorting
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 19 — Sorting

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](#def-b1-sorting-comparison-sort) used today, [quicksort](#def-b1-sorting-quicksort) and [merge sort](#def-b1-sorting-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](#def-b1-sorting-quicksort), with a proved invariant ([Proposition 12.5](https://one-course.com/books/computer-science/3/en/chapter/12-program-correctness#prop-b1-program-correctness-partition)). Recurrences such as $T(n) = 2T(n/2) + n$ and the harmonic numbers $H_n = 1 + \frac12 + \dots + \frac1n \approx \ln n$ were met in [Chapter 13](https://one-course.com/books/computer-science/3/en/chapter/13-asymptotic-analysis-and-recurrences#ch-b1-asymptotic-analysis). [Heapsort](https://one-course.com/books/computer-science/3/en/chapter/18-heaps-and-priority-queues#met-b1-heaps-heapsort) sorts [in place](#def-b1-sorting-comparison-sort) in $\Theta(n \log n)$ ([Method 18.7](https://one-course.com/books/computer-science/3/en/chapter/18-heaps-and-priority-queues#met-b1-heaps-heapsort)). 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)$ memory beyond the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), or $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 $a$ is a pair of positions $i < j$ with $a_i > a_j$.

A sorted sequence has no [inversion](#def-b1-sorting-inversion); a reversed one has all $n(n - 1)/2$. Each exchange of two neighbours removes exactly one [inversion](#def-b1-sorting-inversion), which is why insertion sort, which only exchanges neighbours, costs as many exchanges as the input has [inversions](#def-b1-sorting-inversion) ([Exercise 19.8](#exo-b1-sorting-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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-sorting/img-2360185e6498.jpg)

*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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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.

```c
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](#def-b1-sorting-quicksort) code/bachelor-1/19-sorting/listings/sorts.c*

**Proposition 19.5 (Quicksort is correct).**

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

**Proof.** By strong induction on $m = hi - lo$. A slice of fewer than 2 elements is sorted. Otherwise the partition returns $k$ with $a[lo..k)$ smaller than $a[k]$ and $a(k..hi)$ at least $a[k]$ ([Proposition 12.5](https://one-course.com/books/computer-science/3/en/chapter/12-program-correctness#prop-b1-program-correctness-partition)). Both parts have fewer than $m$ 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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-sorting/fig-95ecded08833.svg)

*[Quicksort](#def-b1-sorting-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.*

The partition of $m$ elements makes $m - 1$ comparisons. When the [pivot](#def-b1-sorting-quicksort) is always the largest element, as on a sorted [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) with the last element as [pivot](#def-b1-sorting-quicksort), one part is empty, and the total is $(n - 1) + (n - 2) + \dots + 1 = n(n - 1)/2$: $\Theta(n^2)$. When the [pivot](#def-b1-sorting-quicksort) always splits evenly, the recurrence $C(n) = 2C(n/2) + n - 1$ gives $\Theta(n \log n)$. What happens on average?

**Theorem 19.6 (Average comparisons of quicksort).**

Over the $n!$ orders of $n$ distinct keys, all equally likely, [quicksort](#def-b1-sorting-quicksort) makes on average $C(n) = 2(n + 1)H_n - 4n$ comparisons, about $2n \ln n \approx 1.39\, n \log_2 n$.

**Proof of the recurrence.** The [pivot](#def-b1-sorting-quicksort) is the last element; in exactly $(n - 1)!$ of the $n!$ orders it has rank $k + 1$, for each $k = 0, \dots, n -
1$, leaving $k$ smaller and $n - 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)!$ orders each part comes in all its orders equally often. Hence $C(0) = C(1) = 0$ and

$$
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](#exo-b1-sorting-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 \leq 8$, and only for this program; the proof covers every $n$. The fair-order assumption is the weak point: input is often sorted, or nearly. Three changes make [quicksort](#def-b1-sorting-quicksort) robust. The [pivot](#def-b1-sorting-quicksort) 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_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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array).

```c
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](#def-b1-sorting-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](#exo-b1-sorting-5)). The [three-way partition](#def-b1-sorting-quicksort) puts them in the middle, which is left out of the recursion.

```c
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](#def-b1-sorting-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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) recursively and merges them.

```c
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](#def-b1-sorting-merge-sort), and bottom-up [merge sort](#def-b1-sorting-merge-sort) code/bachelor-1/19-sorting/listings/sorts.c*

A [merge](#def-b1-sorting-merge-sort) of $m$ elements makes at most $m - 1$ comparisons. The top-down version splits recursively; the bottom-up version [merges](#def-b1-sorting-merge-sort) runs of width 1, then 2, 4, and so on, with no recursion. Both make at most $W(n) = W(\lfloor n/2 \rfloor)
+ W(\lceil n/2 \rceil) + n - 1$ comparisons, which is $n \log_2 n - n + 1$ for $n = 2^k$ (induction: $2(2^{k-1}(k - 1) -
2^{k-1} + 1) + 2^k - 1 = k2^k - 2^k + 1$). On a tie the [merge](#def-b1-sorting-merge-sort) takes the element of the left run first, which makes [merge sort](#def-b1-sorting-merge-sort) [stable](#def-b1-sorting-stable). Its price is an extra [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of $n$ 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](#def-b1-sorting-comparison-sort) for inputs of size $n$ is the [binary tree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-binary-tree) whose [internal nodes](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) are the comparisons the sort makes, with one [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) for each outcome, and whose leaves are the outputs. An input follows one path from the root to a [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree); 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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-sorting/fig-6a6015860fca.svg)

*The [comparison tree](#def-b1-sorting-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.*

**Theorem 19.9 (Lower bound for comparison sorts).**

Every [comparison sort](#def-b1-sorting-comparison-sort) makes at least $\lceil \log_2 n! \rceil$ comparisons on some input of $n$ distinct keys, and $\log_2 n! \geq \frac n2 \log_2 \frac n2$: the worst case is in $\Omega(n \log n)$.

**Proof.** The $n!$ orders of $n$ distinct keys need $n!$ different outputs, so the [comparison tree](#def-b1-sorting-comparison-tree) has at least $n!$ leaves. A [binary tree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-binary-tree) of height $h$ has at most $2^h$ leaves, so $2^h \geq n!$ and $h \geq \lceil \log_2 n! \rceil$. Finally, $n!$ has at least $n/2$ factors at least $n/2$, so $n! \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 $\lceil \log_2 n! \rceil$ against the worst cases of three sorts.*

[Merge sort](#def-b1-sorting-merge-sort) stays within about 10 % of the bound; [merge](#def-b1-sorting-merge-sort) insertion, the method of the problem, meets it exactly up to $n =
11$, then is off by one. The same argument bounds the average: a [binary tree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-binary-tree) with $N$ leaves has an average [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) depth at least $\log_2 N$, so even on average a [comparison sort](#def-b1-sorting-comparison-sort) makes at least $\log_2 n!$ comparisons. [Quicksort](#def-b1-sorting-quicksort)’s $1.39\, n
\log_2 n$ is, for large $n$, 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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-sorting/fig-3d7e2c11f1bf.svg)

*Comparisons from [Output 19.4](#out-b1-sorting-counts), averaged over 200 random orders. [Quicksort](#def-b1-sorting-quicksort) on sorted input leaves the chart at $n = 36$ (630 comparisons). [Merge sort](#def-b1-sorting-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](#lst-b1-sorting-quicksort), [19.2](#lst-b1-sorting-quicksort-good) and [19.4](#lst-b1-sorting-merge) and of heapsort; `qs+` is [Listing 19.2](#lst-b1-sorting-quicksort-good).*

## 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 $n$ keys in $\{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 $d$ digits by $d$ passes of a [stable sort](#def-b1-sorting-stable) on one digit, from the last digit to the first.

```c
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](#def-b1-sorting-radix) on one decimal digit code/bachelor-1/19-sorting/listings/radix.c*

[Counting sort](#def-b1-sorting-radix) costs $\Theta(n + k)$ and is [stable](#def-b1-sorting-stable), since keys are copied in input order into their block. [Radix sort](#def-b1-sorting-radix) costs $\Theta(d(n + k))$: linear in $n$ 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](#def-b1-sorting-radix) 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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-sorting/fig-d8e797451ab1.svg)

*The passes of [Output 19.5](#out-b1-sorting-radix-demo). The arrows follow 457 and 355 into the pass on the tens: equal digits, so the [stable](#def-b1-sorting-stable) pass leaves them in the order the units gave them.*

**Proposition 19.11 (Radix sort is correct).**

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

The proof, by induction on $j$, rests on the stability of each pass ([Exercise 19.12](#exo-b1-sorting-12)); with an unstable pass, it fails ([Exercise 19.6](#exo-b1-sorting-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](#def-b1-sorting-radix) 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](#def-b1-sorting-radix), 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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-sorting/img-50b96164270b.jpg)

*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](#def-b1-sorting-quicksort) that counts its recursion depth and switches to heapsort on a part once the depth passes a limit proportional to $\log n$; small parts are left to insertion sort.

[Introsort](#def-b1-sorting-introsort) keeps [quicksort](#def-b1-sorting-quicksort)’s speed on ordinary input and heapsort’s $O(n \log n)$ guarantee on inputs that defeat the [pivot](#def-b1-sorting-quicksort) choice. The C++ standard requires of `std::sort` $O(n \log n)$ comparisons in the worst case, and allows it to be unstable; `std::stable_sort` is the [stable](#def-b1-sorting-stable) one.

**Facts as of 2026.**

The GNU C++ library implements `std::sort` as an [introsort](#def-b1-sorting-introsort): a depth limit of $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](#def-b1-sorting-stable), adaptive [merge sort](#def-b1-sorting-merge-sort) that finds the runs already sorted in the input and [merges](#def-b1-sorting-merge-sort) them; its [merge](#def-b1-sorting-merge-sort) 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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) for every comparison, which the sorts of this chapter avoid; [radix sort](#def-b1-sorting-radix), with nine passes over the data and no comparison, is the fastest here. Measured times depend on the machine and the [compiler](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-compiler), and say nothing about the worst case.

## 19.7 Exercises

**Exercise 19.1 ★.**

Apply Lomuto’s partition, with the last element as [pivot](#def-b1-sorting-quicksort), to $[3, 8, 2, 5, 1, 4, 7, 6]$. Give the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) and the [pivot](#def-b1-sorting-quicksort)’s index.

**Solution of Exercise 19.1.**

The [pivot](#def-b1-sorting-quicksort) 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]$, [pivot](#def-b1-sorting-quicksort) at index 5, after 7 comparisons.

**Exercise 19.2 ★.**

[Merge](#def-b1-sorting-merge-sort) $[1, 4, 7, 9]$ and $[2, 3, 8, 10, 11]$, and count the comparisons.

**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]$ in 7 comparisons.

**Exercise 19.3 ★.**

[Counting sort](#def-b1-sorting-radix) is applied to $[3, 1, 4, 1, 5, 2, 0, 3]$ with $k = 6$. Give the count [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), the block starts and the output.

**Solution of Exercise 19.3.**

Counts for 0 to 5: $1, 2, 1, 2, 1, 1$. Block starts: $0, 1, 3, 4, 6, 7$. Output: $[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, \mathrm{a}), (1, \mathrm{b}), (2, \mathrm{c}), (1, \mathrm{d})$ are sorted by their number. Which outputs are those of a [stable sort](#def-b1-sorting-stable)? Is selection sort, which exchanges the minimum of the rest with the current element, [stable](#def-b1-sorting-stable)?

**Solution of Exercise 19.4.**

Only $(1, \mathrm{b}), (1, \mathrm{d}), (2, \mathrm{a}), (2, \mathrm{c})$. Selection sort is not [stable](#def-b1-sorting-stable): on $(2,
\mathrm{a}), (2, \mathrm{c}), (1, \mathrm{b})$, the first exchange moves $(2, \mathrm{a})$ behind $(2, \mathrm{c})$, and the output is $(1, \mathrm{b}), (2, \mathrm{c}), (2, \mathrm{a})$.

**Exercise 19.5 ★★.**

Explain the counts of the basic [quicksort](#def-b1-sorting-quicksort) on $n$ equal keys, and why the three-way version makes $2n$ 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 of Exercise 19.5.**

With all keys equal, no key is smaller than the [pivot](#def-b1-sorting-quicksort): the partition makes $m - 1$ comparisons, leaves the left part empty and the right part with $m - 1$ keys. In all $(n - 1) + \dots + 1 = n(n - 1)/2$, which is 499 500 for $n =
1000$. The [three-way partition](#def-b1-sorting-quicksort) compares each key twice (not smaller, not larger), puts all of them in the middle, and recurses on two empty parts: $2n$.

**Exercise 19.6 ★★.**

This [counting sort](#def-b1-sorting-radix) fills each digit’s block from its end. Show that it sorts by one digit correctly, explain the output of a [radix sort](#def-b1-sorting-radix) built on it, and repair it.

```c
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](#def-b1-sorting-radix) of the keys of [Output 19.5](#out-b1-sorting-radix-demo). Some lines are left out.*

**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](#def-b1-sorting-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](#def-b1-sorting-stable) applied twice. In which order must the two sorts be applied? Test the result against a sort on the pair.

**Solution of Exercise 19.7.**

Sort by date first, then by member, with a [stable sort](#def-b1-sorting-stable): 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](#def-b1-sorting-inversion).

**Solution of Exercise 19.8.**

Exchanging two neighbours $a_j > a_{j+1}$ removes the [inversion](#def-b1-sorting-inversion) they form and changes no other pair’s relative order: the number of [inversions](#def-b1-sorting-inversion) drops by exactly 1. Insertion sort exchanges only such neighbours, and stops with a sorted [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), which has no [inversion](#def-b1-sorting-inversion). So it makes exactly as many exchanges as there were [inversions](#def-b1-sorting-inversion).

**Exercise 19.9 ★★.**

Compute $\lceil \log_2 12! \rceil$. What does it say about sorting 12 keys? Compare with [merge sort](#def-b1-sorting-merge-sort) and [merge](#def-b1-sorting-merge-sort) insertion in [Output 19.3](#out-b1-sorting-lower-bound).

**Solution of Exercise 19.9.**

$12! = 479\,001\,600$ and $\log_2 12! \approx 28.84$: every [comparison sort](#def-b1-sorting-comparison-sort) needs at least 29 comparisons for some order of 12 keys. [Merge sort](#def-b1-sorting-merge-sort) needs 33 in its worst case, [merge](#def-b1-sorting-merge-sort) insertion 30. The bound does not say whether 29 can be reached.

**Exercise 19.10 ★★★.**

Solve the recurrence of [Theorem 19.6](#thm-b1-sorting-qs-average): multiply by $n$, subtract the equation for $n - 1$, divide by $n(n + 1)$, and sum.

**Solution of Exercise 19.10.**

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

$$
\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) = 0$. Hence $C(n) = 2(n + 1)H_n - 4n$; with $H_n \approx \ln n$, $C(n) \approx 2n \ln n$.

**Exercise 19.11 ★★★.**

Count the [inversions](#def-b1-sorting-inversion) of an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) in $O(n \log n)$ by modifying [merge sort](#def-b1-sorting-merge-sort), and test against the quadratic count.

**Solution of Exercise 19.11.**

```c
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](#def-b1-sorting-inversion) while merging code/bachelor-1/19-sorting/exercises/inversions.c*

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

**Exercise 19.12 ★★★.**

Prove [Proposition 19.11](#prop-b1-sorting-radix) by induction on $j$.

**Solution of Exercise 19.12.**

For $j = 0$ there is nothing to prove. Suppose the keys sorted by their last $j$ digits before the pass on digit $j + 1$. Take two keys $x$ and $y$. If their digits $j + 1$ differ, the pass orders them by that digit, which decides the order of their last $j + 1$ digits. If they are equal, the pass, being [stable](#def-b1-sorting-stable), leaves $x$ and $y$ in their previous order, the order of their last $j$ digits, which is then the order of their last $j + 1$ digits. So after the pass the keys are sorted by their last $j + 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](#def-b1-sorting-merge-sort) and *[merge](#def-b1-sorting-merge-sort) insertion*, counting the comparisons with a key type that counts them.

```python
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](#def-b1-sorting-merge-sort) 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 $\lceil \log_2 120 \rceil$ , and conclude that no [comparison sort](#def-b1-sorting-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_2 120$ say?
3. How many leaves at least has the [comparison tree](#def-b1-sorting-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](#def-b1-sorting-comparison-tree) of height 7 with 120 leaves has at most 8 leaves at depth 6 or less. (Extend each [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) at depth $d$ to the $2^{7 - d}$ positions below it at depth 7.) How many does [merge](#def-b1-sorting-merge-sort) insertion have?
5. After the first three comparisons of [merge](#def-b1-sorting-merge-sort) insertion, how many of the 120 orders are still possible? Why can at most $2^4$ remain after three comparisons of any method that always finishes in seven?
6. For $n = 4$ , compute the bound, and find a method meeting it.

**Part II — Two familiar methods.**

7. Which input makes insertion sort take 10 comparisons on five keys, and which 4?
8. Explain insertion sort’s average, 7.72, from the [inversions](#def-b1-sorting-inversion) .
9. Compute [merge sort](#def-b1-sorting-merge-sort) ’s worst case on five keys from the recurrence $W(n)$ .
10. Find an order of five keys on which [merge sort](#def-b1-sorting-merge-sort) makes 8 comparisons.
11. Why does [merge sort](#def-b1-sorting-merge-sort) never take fewer than 5 comparisons on five keys?
12. Which of the two methods is closer to the bound?

**Part III — Merge insertion.**

13. After the first three comparisons, what is known about $a, b, c, d$ ?
14. Why does inserting $e$ into the chain $a < b < d$ cost at most 2 comparisons?
15. Why does $c$ need to be compared only with the elements below $d$ , and why are there at most three of them?
16. Count the comparisons of the method in the worst case.
17. Trace the method on the order $(4, 1, 3, 0, 2)$ of the keys $0, \dots, 4$ assigned to $a, \dots, e$ .
18. Why does inserting $e$ before $c$ give a better worst case than inserting $c$ first?

**Part IV — Checking every order.**

19. What does the program check on each of the 120 orders?
20. Why is checking all 120 orders a proof for five distinct keys, and why are distinct keys enough?
21. How many orders take only 6 comparisons? Is that compatible with the lower bound?
22. The general method sorts $n$ keys in $\sum_{k=1}^{n} \lceil \log_2 \frac{3k}{4} \rceil$ comparisons. Check this for $n = 5$ and compare with the bound for $n = 12$ .
23. Why is an exhaustive check impossible for $n = 20$ ?
24. State the named result: *five keys can be sorted in seven comparisons, and no method does it in six* .

**Solution of Problem 19.1.**

**1.** $2^6 = 64 < 120 \leq 128 = 2^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_2 120 \approx
6.91$; [merge](#def-b1-sorting-merge-sort) insertion’s mean, 6.93, is almost there.

**3.** At least 120 leaves; at most $2^7 = 128$.

**4.** A [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) at depth $d \leq 6$ takes at least 2 of the 128 positions at depth 7, a [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) at depth 7 one: $2x +
(120 - x) \leq 128$, so $x \leq 8$. [Merge](#def-b1-sorting-merge-sort) insertion has exactly 8 orders sorted in 6 comparisons.

**5.** $a < b < d$ and $c < d$ leave 3 orders of $a, b, c, d$ ($c$ before $a$, between $a$ and $b$, or between $b$ and $d$), and $e$ can be in any of 5 places: 15 orders. After three comparisons, the leaves still reachable must fit in a [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of height 4, which has at most 16 leaves.

**6.** $\lceil \log_2 24 \rceil = 5$. [Merge sort](#def-b1-sorting-merge-sort) sorts 4 keys in at most $1 + 1 + 3 = 5$ comparisons.

**7.** 10 on the reversed order $(4, 3, 2, 1, 0)$, which has 10 [inversions](#def-b1-sorting-inversion); 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 = 5$ [inversions](#def-b1-sorting-inversion), and the element at position $i$ reaches the front with probability $1/(i + 1)$: $5 + 4 - (\frac12 + \frac13 + \frac14 + \frac15) \approx 7.72$.

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

**10.** The order $(0, 3, 2, 1, 4)$ (found by the program): every [merge](#def-b1-sorting-merge-sort) runs to its last element.

**11.** Each [merge](#def-b1-sorting-merge-sort) of $p$ and $q$ elements makes at least $\min(p, q)$ comparisons: $1 + (1 + 1) + 2 = 5$.

**12.** [Merge sort](#def-b1-sorting-merge-sort): 8 against 10, one above the bound.

**13.** $a < b < d$ and $c < d$; nothing about $e$.

**14.** Binary search in a chain of 3 has 4 possible places, and $\lceil \log_2 4 \rceil = 2$.

**15.** $c < d$, so its place is among the keys below $d$: $a$, $b$, and $e$ if $e < d$. Three keys give 4 places, 2 comparisons.

**16.** $3 + 2 + 2 = 7$.

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

**18.** Inserting $c$ first costs 2 comparisons (among $a$, $b$), but leaves a chain of 4 for $e$, with 5 places: 3 comparisons, 8 in all. Inserting $e$ first keeps both insertions at 4 places.

**19.** That the result is sorted, and how many comparisons it took.

**20.** A [comparison sort](#def-b1-sorting-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, \dots, 5$ are $0, 1, 2, 2, 2$: 7. For 12 keys the method needs 30, one more than the bound 29.

**23.** $20! \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](#def-b1-sorting-merge-sort) insertion sorts every one of the 120 orders in at most seven, as the exhaustive check confirms ([Output 19.10](#out-b1-sorting-sort5)).
