---
title: "Divide and Conquer"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 27
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/27-divide-and-conquer
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 27 — Divide and Conquer

A teacher has $1000$ exam papers to put in alphabetical order. She splits the pile in two and gives each half to a helper; each helper splits again and passes the halves on, until someone holds a single paper, which is sorted. Then the sorted piles come back up: at each level, two sorted piles are merged into one by looking only at their top papers. Nobody ever compares two papers far apart in the order, and the work is done in a small number of rounds.

This chapter turns that idea into a method: split a problem into smaller ones of the same kind, solve them, and combine their answers. It gives [merge sort](#def-g12-divide-and-conquer-merge), which sorts far faster than the sorts of the earlier chapters; a power computed in a handful of multiplications; and an image turned a quarter in place. It also shows where the method does not pay.

**You already know.**

A [recursive function](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#def-g12-recursion-recursion) calls itself on smaller inputs, and is proved by induction (chapter [22](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#ch-g12-recursion)). Binary search halves a sorted list at each step, and its cost is the [number of halvings](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#def-g11-cost-of-an-algorithm-halvings) $h(n)$, the whole number with $2^h \le n < 2^{h+1}$ (chapter [17](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#ch-g11-cost-of-an-algorithm)). Insertion sort makes up to about $n^2/2$ comparisons (the same chapter). A picture is a grid of numbers (Book 1, grade 9).

## 27.1 Split, solve, combine

**Definition 27.1 (Divide and conquer).**

*Divide and conquer* is a way of designing algorithms in three steps: *divide* the problem into smaller problems of the same kind; *solve* each of them, by the same method, until they are small enough to be solved directly; *combine* their solutions into a solution of the whole.

Binary search is the simplest case: one comparison divides the list into two halves, only one of which can hold the value; nothing is left to combine. Its cost is the [number of halvings](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#def-g11-cost-of-an-algorithm-halvings). The algorithms below solve both halves, and their cost depends on how much the combining step costs.

**Notation 27.2 (Binary logarithm).**

For $n > 0$, $\log_2 n$ is the number $y$ with $2^y = n$: $\log_2 8 = 3$, $\log_2 1024 = 10$. It is the logarithm of the mathematics book, in base $2$. For a whole number $n \ge 1$, the [number of halvings](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#def-g11-cost-of-an-algorithm-halvings) is $h(n) = \lfloor \log_2 n \rfloor$, the whole part of $\log_2 n$.

## 27.2 Merge sort

**Definition 27.3 (Merge, merge sort).**

To *merge* two sorted lists is to make one sorted list of all their elements, by repeatedly moving the smaller of their two first elements to the output. *Merge sort* sorts a list by splitting it into two halves, sorting each by merge sort, and merging the results; a list of $0$ or $1$ element is already sorted.

```python
def merge(a, b):
    """Merge two sorted lists into one sorted list; also count the comparisons."""
    out, i, j, comparisons = [], 0, 0, 0
    while i < len(a) and j < len(b):     # invariant: out is sorted, and holds the
        comparisons += 1                 # i smallest of a and j smallest of b
        if a[i] <= b[j]:
            out.append(a[i])
            i += 1
        else:
            out.append(b[j])
            j += 1
    out += a[i:] + b[j:]                 # one of the two is empty: no comparison
    return out, comparisons


if __name__ == "__main__":
    print(merge([3, 8, 12, 20], [1, 9, 10, 25, 30]))
    print(merge([1, 2, 3], [4, 5, 6]), merge([], [7, 8]))
```

***Listing 27.1.** Merging two sorted lists, with a count of the comparisons. code/grade-12/06-divide-and-conquer/listings/merge.py*

```
$ python merge.py
([1, 3, 8, 9, 10, 12, 20, 25, 30], 7)
([1, 2, 3, 4, 5, 6], 3) ([7, 8], 0)
```

***Output 27.1.** Lengths $4$ and $5$ merged in $7$ comparisons; when one list runs out, the rest of the other is copied without comparing.*

![One step of merge. The grey elements are already in out, which is sorted and holds the smallest of a and of b. Only a(i) and b(j) are compared: the smaller is the next element.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-divide-and-conquer/fig-ca59fe272eb5.svg)

*One step of `merge`. The grey elements are already in `out`, which is sorted and holds the smallest of `a` and of `b`. Only `a[i]` and `b[j]` are compared: the smaller is the next element.*

```python
import random

from merge import merge


def merge_sort(t):
    """Return t sorted, and the number of comparisons made."""
    if len(t) <= 1:
        return list(t), 0
    mid = len(t) // 2
    left, c1 = merge_sort(t[:mid])           # divide, and solve each half
    right, c2 = merge_sort(t[mid:])
    merged, c3 = merge(left, right)          # combine
    return merged, c1 + c2 + c3


if __name__ == "__main__":
    print(merge_sort([38, 27, 43, 3, 9, 82, 10, 5]))
    rng = random.Random(6)
    t = [rng.randint(0, 999) for _ in range(1000)]
    s, c = merge_sort(t)
    print("1000 numbers:", s == sorted(t), "| comparisons:", c)
```

***Listing 27.2.** [Merge sort](#def-g12-divide-and-conquer-merge): divide, solve both halves, combine. code/grade-12/06-divide-and-conquer/listings/merge_sort.py*

```
$ python merge_sort.py
([3, 5, 9, 10, 27, 38, 43, 82], 17)
1000 numbers: True | comparisons: 8705
```

***Output 27.2.** Eight numbers in $17$ comparisons; a thousand in $8705$.*

![Merge sort on eight numbers: three levels of splitting, then three levels of merging (shaded). Each level of merging handles all eight numbers once.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-divide-and-conquer/fig-096a68020bca.svg)

*[Merge sort](#def-g12-divide-and-conquer-merge) on eight numbers: three levels of splitting, then three levels of merging (shaded). Each level of merging handles all eight numbers once.*

How many comparisons? Take $n = 2^h$. The splitting goes down $h$ levels, to lists of one element. At each level of merging, the [merges](#def-g12-divide-and-conquer-merge) together output all $n$ elements, and a [merge](#def-g12-divide-and-conquer-merge) makes at most one comparison per element output: at most $n$ per level, so at most $n \cdot h = n \log_2 n$ in all (exercise [27.8](#exo-g12-divide-and-conquer-8)). Insertion sort can need about $n^2/2$.

```python
import random

from merge_sort import merge_sort

rng = random.Random(1)
print(f"{'n':>5} {'h':>3} {'sorted input':>13} {'random input':>13}"
      f" {'n*h':>6} {'n*n/2':>9}")
for h in range(1, 11):
    n = 2 ** h
    t = list(range(n))
    shuffled = rng.sample(t, n)
    print(f"{n:5} {h:3} {merge_sort(t)[1]:13} {merge_sort(shuffled)[1]:13}"
          f" {n * h:6} {n * n // 2:9}")
```

***Listing 27.3.** Comparisons counted, against $n h$ and $n^2/2$. code/grade-12/06-divide-and-conquer/listings/count_vs_nlogn.py*

```
$ python count_vs_nlogn.py
    n   h  sorted input  random input    n*h     n*n/2
    2   1             1             1      2         2
    4   2             4             5      8         8
    8   3            12            16     24        32
   16   4            32            45     64       128
   32   5            80           128    160       512
   64   6           192           307    384      2048
  128   7           448           742    896      8192
  256   8          1024          1736   2048     32768
  512   9          2304          3964   4608    131072
 1024  10          5120          8941  10240    524288
```

***Output 27.3.** A sorted input needs exactly $n h / 2$; a random one a little less than $n h$.*

![Comparisons of merge sort on random lists of 2 to 8192 numbers, from figures/comparisons.py, both axes doubling at each mark. The count stays just under n _2 n; at 8192 numbers it is 96\,178, against 33\,554\,432 for n2/2.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-divide-and-conquer/fig-c2f019006817.svg)

*Comparisons of [merge sort](#def-g12-divide-and-conquer-merge) on random lists of $2$ to $8192$ numbers, from `figures/comparisons.py`, both axes doubling at each mark. The count stays just under $n \log_2 n$; at $8192$ numbers it is $96\,178$, against $33\,554\,432$ for $n^2/2$.*

Comparisons are not the whole cost: [merge sort](#def-g12-divide-and-conquer-merge) also copies lists. The clock agrees with the count all the same.

```python
"""Merge sort against insertion sort, timed on the author's laptop."""
import random
import time

from merge_sort import merge_sort


def insertion_sort(t):
    t = list(t)
    for i in range(1, len(t)):
        x, j = t[i], i - 1
        while j >= 0 and t[j] > x:
            t[j + 1] = t[j]
            j -= 1
        t[j + 1] = x
    return t


def best_time(f, t, repeat=3):
    times = []
    for _ in range(repeat):
        start = time.perf_counter()
        f(t)
        times.append(time.perf_counter() - start)
    return min(times)


if __name__ == "__main__":
    rng = random.Random(2)
    for n in [250, 500, 1000, 2000, 4000]:
        t = [rng.random() for _ in range(n)]
        merge_t, insert_t = best_time(merge_sort, t), best_time(insertion_sort, t)
        ratio = insert_t / merge_t
        print(f"n = {n:4}: merge {merge_t * 1000:7.2f} ms"
              f"   insertion {insert_t * 1000:8.2f} ms   ratio {ratio:5.1f}")
```

***Listing 27.4.** [Merge sort](#def-g12-divide-and-conquer-merge) and insertion sort, timed. code/grade-12/06-divide-and-conquer/listings/measure_sorts.py*

```
$ python measure_sorts.py
n =  250: merge    0.15 ms   insertion     0.37 ms   ratio   2.4
n =  500: merge    0.37 ms   insertion     1.70 ms   ratio   4.6
n = 1000: merge    0.76 ms   insertion     7.03 ms   ratio   9.2
n = 2000: merge    1.68 ms   insertion    30.51 ms   ratio  18.2
n = 4000: merge    3.88 ms   insertion   135.06 ms   ratio  34.8
```

***Output 27.4.** On the author’s laptop. Each doubling of $n$ about doubles the time of [merge sort](#def-g12-divide-and-conquer-merge) and quadruples that of insertion sort.*

![Times measured on the author’s laptop by figures/measured_sorts.py, on random lists of 250 to 8000 numbers. Insertion sort’s curve bends upwards like n2; merge sort’s stays near the axis, at about 8 milliseconds for 8000 numbers against about 490.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-divide-and-conquer/fig-5dca02148b42.svg)

*Times measured on the author’s laptop by `figures/measured_sorts.py`, on random lists of $250$ to $8000$ numbers. Insertion sort’s curve bends upwards like $n^2$; [merge sort](#def-g12-divide-and-conquer-merge)’s stays near the axis, at about $8$ milliseconds for $8000$ numbers against about $490$.*

## 27.3 Fast exponentiation

Computing $x^{1000}$ by multiplying by $x$ again and again takes $999$ multiplications. But $x^{1000} =
(x^{500})^2$, and $x^{500} = (x^{250})^2$: one problem of half the size, and one multiplication.

**Method 27.4 (Fast exponentiation).**

*Fast exponentiation* computes $x^n$ from $y = x^{\lfloor n/2 \rfloor}$: $x^n = y^2$ if $n$ is even, $x^n = y^2 \times x$ if $n$ is odd; $x^0 = 1$ and $x^1 = x$. Each step costs one or two multiplications, and there are $h(n)$ steps: at most $2 \lfloor \log_2 n \rfloor$ multiplications.

```python
def power(x, n):
    """x to the power n, by squaring; returns (value, multiplications)."""
    if n == 0:
        return 1, 0
    if n == 1:
        return x, 0
    half, m = power(x, n // 2)          # one smaller problem, used twice
    if n % 2 == 0:
        return half * half, m + 1
    return half * half * x, m + 2


def power_loop(x, n):
    """The same, reading the binary digits of n from the right."""
    result, square = 1, x
    while n > 0:
        if n % 2 == 1:
            result *= square
        square *= square
        n //= 2
    return result


def power_mod(x, n, m):
    """x to the power n, modulo m: every intermediate value stays below m."""
    result, square = 1, x % m
    while n > 0:
        if n % 2 == 1:
            result = result * square % m
        square = square * square % m
        n //= 2
    return result


if __name__ == "__main__":
    for n in [10, 13, 64, 100, 1000]:
        value, m = power(3, n)
        print(f"3^{n:<4}: {m:2} multiplications instead of {n - 1:3};"
              f" same as the loop: {value == power_loop(3, n)}")
    print(power_mod(7, 10**18, 1_000_003), pow(7, 10**18, 1_000_003))
```

***Listing 27.5.** [Fast exponentiation](#met-g12-divide-and-conquer-fast-power), recursive, with a loop, and modulo $m$. code/grade-12/06-divide-and-conquer/listings/fast_power.py*

```
$ python fast_power.py
3^10  :  4 multiplications instead of   9; same as the loop: True
3^13  :  5 multiplications instead of  12; same as the loop: True
3^64  :  6 multiplications instead of  63; same as the loop: True
3^100 :  8 multiplications instead of  99; same as the loop: True
3^1000: 14 multiplications instead of 999; same as the loop: True
32502 32502
```

***Output 27.5.** $3^{1000}$ in $14$ multiplications; the modular version agrees with Python’s own `pow`.*

The loop reads the binary digits of $n$ from the right: `square` runs through $x$, $x^2$, $x^4$, $x^8$, …, and `result` takes in the powers whose digit is $1$; $13 = 8 + 4 + 1$ gives $x^{13} = x^8 \cdot x^4 \cdot x$. The modular version keeps every number below $m$ by taking the remainder after each multiplication: $7^{10^{18}}$ has far too many digits to be written, but its remainder modulo $1\,000\,003$ takes fewer than $120$ multiplications of numbers below $m$. Secure communication relies on exactly this computation (chapter [33](https://one-course.com/books/computer-science/2/en/chapter/33-cryptography-and-secure-communication#ch-g12-secure-communication)).

## 27.4 Rotating an image by quarters

Turning a square picture a quarter turn clockwise sends the pixel in row $r$, column $c$ to row $c$, column $n - 1 - r$. The simplest way writes every pixel into a new grid: it needs a second picture’s worth of memory.

```python
def rotate_copy(grid):
    """A quarter turn clockwise, into a new grid: the row r becomes column n-1-r."""
    n = len(grid)
    out = [[None] * n for _ in range(n)]
    for r in range(n):
        for c in range(n):
            out[c][n - 1 - r] = grid[r][c]
    return out


def show(grid):
    for row in grid:
        print(" ".join(f"{x:>2}" for x in row))


if __name__ == "__main__":
    g = [[4 * r + c for c in range(4)] for r in range(4)]
    show(g)
    print("--- a quarter turn clockwise:")
    show(rotate_copy(g))
```

***Listing 27.6.** A quarter turn into a new grid. code/grade-12/06-divide-and-conquer/listings/rotate_copy.py*

```
$ python rotate_copy.py
 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15
--- a quarter turn clockwise:
12  8  4  0
13  9  5  1
14 10  6  2
15 11  7  3
```

***Output 27.6.** The first row becomes the last column.*

For a picture of side $2^k$, [divide and conquer](#def-g12-divide-and-conquer-dc) turns it in place. Cut it into four quadrants. Move each quadrant to the next place clockwise, top-left to top-right to bottom-right to bottom-left, by swapping four pixels at a time; then turn each quadrant a quarter, by the same method. Only one pixel is ever held aside.

![A 4 × 4 grid turned by quadrants. First the four blocks of 2 × 2 move round clockwise, each keeping its inside unchanged (the shades follow each block); then each block is turned on its own. The result is the output of the copy above.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-divide-and-conquer/fig-7550af88df8f.svg)

*A $4 \times 4$ grid turned by quadrants. First the four blocks of $2 \times 2$ move round clockwise, each keeping its inside unchanged (the shades follow each block); then each block is turned on its own. The result is the output of the copy above.*

```python
from rotate_copy import rotate_copy, show


def rotate_in_place(grid, top=0, left=0, size=None):
    """Rotate the square block of a 2^k grid a quarter turn clockwise, in place."""
    if size is None:
        size = len(grid)
    if size == 1:
        return
    h = size // 2
    for r in range(h):                       # move the four quadrants round:
        for c in range(h):                   # top-left -> top-right -> bottom-right
            a = (top + r, left + c)          # -> bottom-left -> top-left
            b = (top + r, left + h + c)
            d = (top + h + r, left + h + c)
            e = (top + h + r, left + c)
            t = grid[e[0]][e[1]]
            grid[e[0]][e[1]] = grid[d[0]][d[1]]
            grid[d[0]][d[1]] = grid[b[0]][b[1]]
            grid[b[0]][b[1]] = grid[a[0]][a[1]]
            grid[a[0]][a[1]] = t
    for dr, dc in [(0, 0), (0, h), (h, 0), (h, h)]:
        rotate_in_place(grid, top + dr, left + dc, h)   # then turn each quadrant


if __name__ == "__main__":
    g = [[4 * r + c for c in range(4)] for r in range(4)]
    expected = rotate_copy(g)
    rotate_in_place(g)
    show(g)
    print("same as the copy:", g == expected)
```

***Listing 27.7.** The quarter turn by quadrants, in place. code/grade-12/06-divide-and-conquer/listings/rotate_quadrants.py*

```
$ python rotate_quadrants.py
12  8  4  0
13  9  5  1
14 10  6  2
15 11  7  3
same as the copy: True
```

***Output 27.7.** The same grid as the copy.*

The same function turns a real picture. `arrow.pgm` is a picture of $16 \times 16$ grey levels in a plain-text format, a short header and then one number per pixel; the program turns it, writes it to a file, reads it back, and prints both as characters.

```python
"""Read a PGM picture, turn it a quarter by quadrants, write it back."""
import tempfile
from pathlib import Path

from rotate_copy import rotate_copy
from rotate_quadrants import rotate_in_place


def read_pgm(path):
    words = Path(path).read_text().split()
    width, height = int(words[1]), int(words[2])
    values = [int(w) for w in words[4:]]
    return [values[r * width:(r + 1) * width] for r in range(height)]


def write_pgm(path, grid):
    rows = "\n".join(" ".join(str(v) for v in row) for row in grid)
    Path(path).write_text(f"P2\n{len(grid[0])} {len(grid)}\n255\n{rows}\n")


def as_text(grid):
    return ["".join("#" if v < 100 else ("+" if v < 200 else ".") for v in row)
            for row in grid]


picture = read_pgm("arrow.pgm")
turned = [row[:] for row in picture]
rotate_in_place(turned)
with tempfile.TemporaryDirectory() as folder:
    write_pgm(Path(folder) / "arrow_turned.pgm", turned)
    again = read_pgm(Path(folder) / "arrow_turned.pgm")
for before, after in zip(as_text(picture), as_text(again)):
    print(before, "  ", after)
print("same as the copy:", again == rotate_copy(picture), "| pixel sum:",
      sum(map(sum, picture)), sum(map(sum, again)))
```

***Listing 27.8.** A picture turned by quadrants. code/grade-12/06-divide-and-conquer/listings/rotate_image.py*

```
$ python rotate_image.py
................    ................
................    ................
.......##.......    .++.....#.......
......####......    .+......##......
.....######.....    ........###.....
....########....    ........####....
...##########...    .############...
..############..    .#############..
......####......    .#############..
......####......    .############...
......####......    ........####....
......####......    ........###.....
......####......    ........##......
..+...####......    ........#.......
..++..####......    ................
................    ................
same as the copy: True | pixel sum: 43850 43850
```

***Output 27.8.** The arrow pointing up now points right; the small mark at the bottom left went to the top left.*

## 27.5 When it pays, and when it does not

[Divide and conquer](#def-g12-divide-and-conquer-dc) pays when the parts are of similar sizes and combining is cheap. If a split leaves one part almost as large as the whole, as in a split that cuts off one element, the levels are $n$ instead of $\log_2 n$, and a [merge sort](#def-g12-divide-and-conquer-merge) built that way is no faster than insertion sort. On very small inputs, the calls and copies cost more than they save: at $n = 250$ [merge sort](#def-g12-divide-and-conquer-merge) is only about twice as fast. Real sorting functions, Python’s `sorted` among them, [merge](#def-g12-divide-and-conquer-merge) runs of elements but finish small pieces by insertion.

**Remark 27.5.**

The method also finds the largest sum of consecutive elements of a list: the best block lies in the left half, or in the right half, or straddles the middle, and the third case is found in one pass from the middle outwards (exercise [27.15](#exo-g12-divide-and-conquer-15)).

## 27.6 Exercises

**Exercise 27.1 ★.**

[Merge](#def-g12-divide-and-conquer-merge) $[2, 5, 9]$ and $[1, 6, 7, 11]$ step by step. How many comparisons?

**Solution of Exercise 27.1.**

$1 < 2$: out $1$. $2 < 6$: $2$. $5 < 6$: $5$. $9 > 6$: $6$. $9 > 7$: $7$. $9 < 11$: $9$. The first list is empty, and $11$ is copied. The result is $[1, 2, 5, 6, 7, 9, 11]$, after $6$ comparisons.

**Exercise 27.2 ★.**

What are the smallest and the largest numbers of comparisons when merging a list of $3$ elements with one of $4$? Give an example of each.

**Solution of Exercise 27.2.**

At least $3$: each comparison outputs one element, and a list must run out; $[1, 2, 3]$ with $[4, 5, 6, 7]$ needs exactly $3$. At most $3 + 4 - 1 = 6$: the last element is always copied without comparing; $[2, 4, 6]$ with $[1, 3, 5, 7]$ needs $6$.

**Exercise 27.3 ★.**

Draw the splits and the [merges](#def-g12-divide-and-conquer-merge) of `merge_sort` on $[5, 2, 4, 6, 1, 3]$.

**Solution of Exercise 27.3.**

Splits: $[5, 2, 4]$ and $[6, 1, 3]$; then $[5]$ and $[2, 4]$, $[6]$ and $[1, 3]$; then $[2]$, $[4]$, $[1]$, $[3]$. [Merges](#def-g12-divide-and-conquer-merge): $[2, 4]$ and $[1, 3]$; then $[2, 4, 5]$ and $[1, 3, 6]$; then $[1, 2, 3, 4, 5, 6]$.

**Exercise 27.4 ★.**

List the multiplications `power(x, 13)` makes. How many are there?

**Solution of Exercise 27.4.**

`power(x, 13)` asks for `power(x, 6)`, which asks for `power(x, 3)`, which asks for `power(x, 1)`, $x$, with no multiplication. Then $x \cdot x \cdot x = x^3$ (two), $x^3 \cdot x^3 = x^6$ (one), $x^6 \cdot x^6 \cdot x = x^{13}$ (two): five multiplications.

**Exercise 27.5 ★.**

Write `merge_desc(a, b)`, which [merges](#def-g12-divide-and-conquer-merge) two lists sorted in decreasing order.

**Solution of Exercise 27.5.**

The [merge](#def-g12-divide-and-conquer-merge) of the chapter with the comparison reversed: `if a[i] >= b[j]:` takes from `a`, otherwise from `b`; after the loop, `return out + a[i:] + b[j:]`.

**Exercise 27.6 ★★.**

A `merge` has no line after its loop. What does it return for `[1, 4, 9]` and `[2, 3]`? Which tests would have caught it?

**Solution of Exercise 27.6.**

`[1, 2, 3]`: when `b` runs out, $4$ and $9$ are still in `a`, and nothing copies them. A test with lists of different lengths, or where one list ends long before the other, catches it; so does checking `len(out) == len(a) + len(b)`, or comparing with `sorted(a + b)` on random lists.

**Exercise 27.7 ★★.**

The matrix $\begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}^n$ holds the Fibonacci number $\mathrm{fib}(n)$ in its top right corner. Write `fib(n)` with [fast exponentiation](#met-g12-divide-and-conquer-fast-power) of $2 \times 2$ matrices.

**Solution of Exercise 27.7.**

    `def mat_mult(p, q):`

        `return [[sum(p[i][k] * q[k][j] for k in range(2)) for j in range(2)]`

                `for i in range(2)]`

    `def fib(n):`

        `result, square = [[1, 0], [0, 1]], [[1, 1], [1, 0]]`

        `while n > 0:`

            `if n % 2 == 1:`

                `result = mat_mult(result, square)`

            `square = mat_mult(square, square)`

            `n //= 2`

        `return result[0][1]`

The loop of `power_loop`, with matrices and the identity matrix as starting value. `fib(90)` takes $11$ matrix products, against $89$ additions in a loop, and the recursion of chapter [22](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#ch-g12-recursion) would never finish.

**Exercise 27.8 ★★.**

Prove by induction on $h$ that [merge sort](#def-g12-divide-and-conquer-merge) makes at most $n h$ comparisons on a list of $n = 2^h$ elements.

**Solution of Exercise 27.8.**

Let $C(h)$ be the largest number of comparisons on $2^h$ elements. $C(0) = 0 = 2^0 \times 0$. For $h \ge 1$, the two halves have $2^{h-1}$ elements each, so at most $C(h - 1)$ comparisons each, and merging them makes at most $2^h - 1$. If $C(h - 1) \le 2^{h-1}(h - 1)$, then $C(h) \le 2 \cdot 2^{h-1}(h - 1) + 2^h - 1 < 2^h h$.

**Exercise 27.9 ★★.**

Turn the grid of letters with rows `ab`, `cd` a quarter clockwise. Then turn the $4 \times 4$ grid with rows `abcd`, `efgh`, `ijkl`, `mnop` by quadrants, giving the grid after each of the two stages.

**Solution of Exercise 27.9.**

`ab`, `cd` becomes `ca`, `db`. For the $4 \times 4$ grid, moving the quadrants gives the rows `ijab`, `mnef`, `klcd`, `opgh`; turning each quadrant gives `miea`, `njfb`, `okgc`, `plhd`. Check: the first row of the result is the first column read upwards.

**Exercise 27.10 ★★.**

In `merge_sort`, a student writes `mid = len(t) // 2 + 1`. What happens on a list of two elements?

**Solution of Exercise 27.10.**

`mid` is $2$: the left half is the whole list and the right half is empty. The call on the left half is the same call again, and so on, until `RecursionError`. A division must give two parts both smaller than the whole; `len(t) // 2` does for every length at least $2$.

**Exercise 27.11 ★★.**

Write a [merge sort](#def-g12-divide-and-conquer-merge) without recursion: start from runs of one element, and [merge](#def-g12-divide-and-conquer-merge) the runs two by two until one is left.

**Solution of Exercise 27.11.**

    `def merge_sort_bottom_up(t):`

        `runs = [[x] for x in t]`

        `while len(runs) > 1:`

            `runs = [merge(runs[k], runs[k + 1])[0]`

                    `if k + 1 < len(runs) else runs[k]`

                    `for k in range(0, len(runs), 2)]`

        `return runs[0] if runs else []`

Each pass halves the number of runs (an odd one out waits for the next pass): $h(n) + 1$ passes at most, each merging all $n$ elements, the same work as the recursive version.

**Exercise 27.12 ★★★.**

Prove that `power(x, n)` makes at most $2 \lfloor \log_2 n \rfloor$ multiplications for $n \ge 1$, and exactly (number of binary digits of $n$ $- 1$) $+$ (number of digits $1$ $- 1$).

**Solution of Exercise 27.12.**

Write $b(n)$ for the number of binary digits of $n$ and $o(n)$ for its number of digits $1$; claim $m(n) = (b(n) - 1) + (o(n) - 1)$. For $n = 1$: $0 = 0 + 0$. For $n \ge 2$, $\lfloor n/2 \rfloor$ is $n$ without its last binary digit: $b(\lfloor n/2 \rfloor) = b(n) - 1$ and $o(\lfloor n/2 \rfloor) = o(n) - (n \bmod 2)$. The call makes $1 + (n \bmod 2)$ multiplications more than the call on $\lfloor n/2 \rfloor$, so by induction $m(n) = (b(n) - 2) + (o(n) - (n \bmod 2) - 1) + 1 + (n \bmod 2) = (b(n) - 1) + (o(n) - 1)$. Since $o(n) \le b(n)$ and $b(n) - 1 = \lfloor \log_2 n \rfloor$, $m(n) \le 2 \lfloor \log_2 n \rfloor$. For $1000$, written with $10$ digits of which $6$ are $1$: $9 + 5 = 14$, as printed.

**Exercise 27.13 ★★★.**

Write `rotate_layers(grid)`, which turns a square grid of any side in place, ring by ring from the outside, four pixels at a time. Test it against `rotate_copy`.

**Solution of Exercise 27.13.**

    `def rotate_layers(grid):`

        `n = len(grid)`

        `for layer in range(n // 2):`

            `first, last = layer, n - 1 - layer`

            `for k in range(last - first):`

                `top = grid[first][first + k]`

                `grid[first][first + k] = grid[last - k][first]`

                `grid[last - k][first] = grid[last][last - k]`

                `grid[last][last - k] = grid[first + k][last]`

                `grid[first + k][last] = top`

Each ring is turned by moving four cells at a time: left side to top, bottom to left, right to bottom, top to right. It works for every side, odd ones too (the centre stays). The tests compare it with `rotate_copy` on random grids of sides $1$ to $8$.

**Exercise 27.14 ★★★.**

Show that for $n = 2^h$, [merge sort](#def-g12-divide-and-conquer-merge) makes at least $n h / 2$ comparisons on every input: whatever the order, its count is within a factor $2$ of $n \log_2 n$.

**Solution of Exercise 27.14.**

A [merge](#def-g12-divide-and-conquer-merge) of two lists of $p$ elements each makes at least $p$ comparisons: each comparison outputs one element, and the loop stops only when one list is empty. At the level where blocks of $2^k$ elements are merged in pairs, there are $n / 2^{k+1}$ [merges](#def-g12-divide-and-conquer-merge) of at least $2^k$ comparisons: at least $n/2$ per level, and there are $h$ levels. So the count lies between $n h / 2$ and $n h$, whatever the input; the program’s sorted input reaches the lower bound exactly.

**Exercise 27.15 ★★★.**

Write `max_subarray(t)`, the largest sum of a block of consecutive elements of a non-empty list, by [divide and conquer](#def-g12-divide-and-conquer-dc). Test it against the sums of all blocks.

**Solution of Exercise 27.15.**

    `def max_subarray(t):`

        `if len(t) == 1:`

            `return t[0]`

        `mid = len(t) // 2`

        `best = max(max_subarray(t[:mid]), max_subarray(t[mid:]))`

        `s, left = 0, t[mid - 1]`

        `for x in reversed(t[:mid]):`

            `s += x`

            `left = max(left, s)`

        `s, right = 0, t[mid]`

        `for x in t[mid:]:`

            `s += x`

            `right = max(right, s)`

        `return max(best, left + right)`

A block straddling the middle is a block ending at `mid - 1` followed by one starting at `mid`; each part is best chosen on its own. For $[2, -5, 3, 4, -1, 6, -8, 2]$: $3 + 4 - 1 + 6 = 12$. The tests compare with the sums of all blocks on $200$ random lists.

## 27.7 Problem: Counting Inversions

**Problem 27.1.**

Weekend problem — how far apart are two rankings?

Two judges rank the same items. Writing the second ranking in terms of the first’s positions gives a list; each pair of items the judges order differently is an *inversion* of that list, a pair of positions $i < j$ with $t[i] > t[j]$. The program counts inversions by trying every pair, and by a [merge sort](#def-g12-divide-and-conquer-merge) that counts them on the way.

```python
"""How far apart are two rankings? Count the pairs they put in opposite orders."""
import random

from merge import merge


def inversions_brute(t):
    n = len(t)
    return sum(1 for i in range(n) for j in range(i + 1, n) if t[i] > t[j])


def sort_count(t):
    """Return t sorted and its number of inversions, by merge sort."""
    if len(t) <= 1:
        return list(t), 0
    mid = len(t) // 2
    left, x = sort_count(t[:mid])
    right, y = sort_count(t[mid:])
    across, i = 0, 0
    for b in right:                      # pairs (a in left, b in right) with a > b
        while i < len(left) and left[i] <= b:
            i += 1
        across += len(left) - i          # every a from left[i] on is larger than b
    return merge(left, right)[0], x + y + across


def ranking(n, seed):
    items = list(range(n))
    random.Random(seed).shuffle(items)
    return items


def compare(first, second):
    """Inversions of second, written in the positions of first."""
    place = {item: k for k, item in enumerate(first)}
    return [place[item] for item in second]

```

***Listing 27.9.** Inversions, by brute force and by merging. code/grade-12/06-divide-and-conquer/listings/inversions.py*

```python
if __name__ == "__main__":
    judge_a = ["Ada", "Ben", "Cleo", "Dev", "Eli"]
    judge_b = ["Ben", "Ada", "Eli", "Cleo", "Dev"]
    t = compare(judge_a, judge_b)
    print(t, "brute force:", inversions_brute(t), "| by merging:", sort_count(t)[1])
    n = 100_000
    t = compare(ranking(n, 1), ranking(n, 2))
    count = sort_count(t)[1]
    print(f"n = {n}: {count} inversions out of {n * (n - 1) // 2} pairs,"
          f" {count / (n * (n - 1) / 2):.4f} of them")
```

***Listing 27.10.** Two judges, then two random rankings. code/grade-12/06-divide-and-conquer/listings/inversions.py*

```
$ python inversions.py
[1, 0, 4, 2, 3] brute force: 3 | by merging: 3
n = 100000: 2488902981 inversions out of 4999950000 pairs, 0.4978 of them
```

***Output 27.9.** Two judges of five, then two random rankings of $100\,000$ items.*

```python
"""Brute force against merging, timed on the author's laptop."""
import time

from inversions import compare, inversions_brute, ranking, sort_count


def timed(f, t):
    start = time.perf_counter()
    result = f(t)
    return result, time.perf_counter() - start


for n in [1000, 2000, 4000, 8000]:
    t = compare(ranking(n, 1), ranking(n, 2))
    brute, t_brute = timed(inversions_brute, t)
    (_, merged), t_merge = timed(sort_count, t)
    print(f"n = {n:4}: brute {t_brute:6.3f} s   merging {t_merge:6.3f} s"
          f"   ratio {t_brute / t_merge:5.0f}   same count: {brute == merged}")
_, t_merge = timed(sort_count, compare(ranking(100_000, 1), ranking(100_000, 2)))
print(f"n = 100000: merging {t_merge:.2f} s")
```

***Listing 27.11.** The two methods, timed. code/grade-12/06-divide-and-conquer/listings/measure_inversions.py*

```
$ python measure_inversions.py
n = 1000: brute  0.016 s   merging  0.002 s   ratio    10   same count: True
n = 2000: brute  0.056 s   merging  0.003 s   ratio    21   same count: True
n = 4000: brute  0.213 s   merging  0.006 s   ratio    37   same count: True
n = 8000: brute  0.867 s   merging  0.012 s   ratio    73   same count: True
n = 100000: merging 0.20 s
```

***Output 27.10.** On the author’s laptop. Brute force is not even tried at $100\,000$.*

**Part I — Rankings.**

1. In the example of five, which pairs do the judges order differently?
2. What list does `compare` give for two identical rankings, and how many inversions? For two opposite rankings of $n$ items?
3. Why is the number of inversions at most $n(n - 1)/2$ ?
4. Two random rankings: what share of the pairs would you guess to be inverted? Compare with the output.

**Part II — Brute force.**

5. How many pairs does `inversions_brute` examine for $n$ items?
6. From the measured times, by how much does the brute-force time grow when $n$ doubles? Why?
7. Estimate its time for $n = 100\,000$ from the time at $8000$ .

**Part III — Counting while merging.**

8. Split the inversions of a list into three kinds, by where their two positions lie.
9. Which two kinds do the recursive calls count?
10. Why can the third kind be counted on the two sorted halves, although sorting changed the positions?
11. Explain the loop over `right` : why is `len(left) - i` the number of inversions with `b` ?
12. Why does `i` never go back, and what does that make the cost of the loop?
13. Prove, by induction on the length, that `sort_count` returns the number of inversions.

**Part IV — Cost and speed.**

14. How many comparisons does `sort_count` make, roughly, for $n = 2^h$ ?
15. Read the measured ratio of the two methods at each $n$ . How does it grow?
16. From your estimate of question 7, what would the ratio be at $100\,000$ ?
17. From $n = 1000$ to $n = 8000$ , compare the growth of the measured ratio with that of $n / \log_2 n$ .
18. The brute-force method is still useful. For what?
19. The tests check the count at $100\,000$ against no brute force. What do they check instead?
20. State the result: the inversions between the two rankings of $100\,000$ , and the measured ratio at $8000$ .

**Solution of Problem 27.1.**

**1.** `compare` gives $[1, 0, 4, 2, 3]$. The inverted pairs: Ada and Ben; Cleo and Eli; Dev and Eli.

**2.** Identical rankings give $[0, 1, \dots, n - 1]$, with no inversion. Opposite rankings give $[n - 1, \dots, 1, 0]$: every pair is inverted, $n(n - 1)/2$ inversions.

**3.** An inversion is a pair of positions, and there are $n(n - 1)/2$ pairs.

**4.** About half: in a random ranking each pair is as likely in one order as in the other. The output gives $0.4978$.

**5.** $n(n - 1)/2$: every pair.

**6.** About four times: the printed run gives $0.016$, $0.056$, $0.213$ and $0.867$ seconds (another run gives slightly different times). Doubling $n$ about quadruples the number of pairs.

**7.** $0.867 \times (100\,000 / 8000)^2 = 0.867 \times 156.25 \approx 135$ seconds, over two minutes.

**8.** Both positions in the left half; both in the right half; one in each.

**9.** The calls on the halves count the first two kinds, `x` and `y`.

**10.** A pair across the middle joins an element of the left half and one of the right half, and whether the first is larger depends only on the two values, not on where they sit in their halves. Sorting each half moves values only within it.

**11.** `left` is sorted, and the `while` loop stops at the first `left[i]` larger than `b`: every element from there on is larger than `b`, every one before is not. So exactly `len(left) - i` elements of the left half form an inversion with `b`.

**12.** `right` is sorted, so each `b` is at least the one before, and the first element of `left` larger than it can only be further right. `i` moves at most `len(left)` times in all: the loop costs at most `len(left) + len(right)` steps, like a [merge](#def-g12-divide-and-conquer-merge).

**13.** For a list of $0$ or $1$ element, no pair: $0$. Otherwise, by induction `x` and `y` are the inversions within each half, and `across` counts those across, by questions 10 and 11; every inversion is of exactly one kind, so the sum is the number of inversions. The returned list is sorted, by the proof of [merge sort](#def-g12-divide-and-conquer-merge).

**14.** The [merges](#def-g12-divide-and-conquer-merge) make at most $n h$ comparisons and the counting loops about $n h$ more: about $2 n \log_2 n$, against $n^2 / 2$ pairs for brute force.

**15.** $10$, $21$, $37$, $73$ in the printed run: it about doubles each time $n$ doubles.

**16.** About $135 / 0.20 \approx 680$, that is, about $700$.

**17.** $n / \log_2 n$ goes from about $100$ to about $617$, a factor of about $6.2$; the measured ratio goes from $10$ to $73$, a factor of about $7$. They grow at a similar pace; the rest is the different work per step of the two methods, and the noise of the measurements, large for times of a few milliseconds.

**18.** As a reference: it is too simple to be wrong, and on small lists it checks the fast method.

**19.** They compare the fast count with brute force on random lists of every length up to $59$, and keep the count at $100\,000$ fixed to the value printed, so that any later change to the code that alters it is noticed.

**20.** **The two random rankings of $100\,000$ items differ on $2\,488\,902\,981$ of their $4\,999\,950\,000$ pairs ($0.4978$); at $n = 8000$, counting by merging was about $70$ times faster than trying every pair ($73$ in the printed run), and about $700$ times is expected at $100\,000$.**
