本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
27Divide and Conquer
A teacher has 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, 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 calls itself on smaller inputs, and is proved by induction (chapter 22). Binary search halves a sorted list at each step, and its cost is the number of halvings , the whole number with (chapter 17). Insertion sort makes up to about 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. The algorithms below solve both halves, and their cost depends on how much the combining step costs.
Notation 27.2 (Binary logarithm)
For , is the number with : , . It is the logarithm of the mathematics book, in base . For a whole number , the number of halvings is , the whole part of .
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 or element is already sorted.
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]))
$ python merge.py
([1, 3, 8, 9, 10, 12, 20, 25, 30], 7)
([1, 2, 3, 4, 5, 6], 3) ([7, 8], 0)
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.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)
$ python merge_sort.py
([3, 5, 9, 10, 27, 38, 43, 82], 17)
1000 numbers: True | comparisons: 8705
How many comparisons? Take . The splitting goes down levels, to lists of one element. At each level of merging, the merges together output all elements, and a merge makes at most one comparison per element output: at most per level, so at most in all (exercise 27.8). Insertion sort can need about .
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}")
$ 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
figures/comparisons.py, both axes doubling at each mark. The count stays just under ; at numbers it is , against for .Comparisons are not the whole cost: merge sort also copies lists. The clock agrees with the count all the same.
"""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}")
$ 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
figures/measured_sorts.py, on random lists of to numbers. Insertion sort’s curve bends upwards like ; merge sort’s stays near the axis, at about milliseconds for numbers against about .27.3 Fast exponentiation
Computing by multiplying by again and again takes multiplications. But , and : one problem of half the size, and one multiplication.
Method 27.4 (Fast exponentiation)
Fast exponentiation computes from : if is even, if is odd; and . Each step costs one or two multiplications, and there are steps: at most multiplications.
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))
$ 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
pow.The loop reads the binary digits of from the right: square runs through , , , , …, and result takes in the powers whose digit is ; gives . The modular version keeps every number below by taking the remainder after each multiplication: has far too many digits to be written, but its remainder modulo takes fewer than multiplications of numbers below . Secure communication relies on exactly this computation (chapter 33).
27.4 Rotating an image by quarters
Turning a square picture a quarter turn clockwise sends the pixel in row , column to row , column . The simplest way writes every pixel into a new grid: it needs a second picture’s worth of memory.
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))
$ 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
For a picture of side , divide and conquer 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.
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)
$ 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
The same function turns a real picture. arrow.pgm is a picture of 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.
"""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)))
$ python rotate_image.py
................ ................
................ ................
.......##....... .++.....#.......
......####...... .+......##......
.....######..... ........###.....
....########.... ........####....
...##########... .############...
..############.. .#############..
......####...... .#############..
......####...... .############...
......####...... ........####....
......####...... ........###.....
......####...... ........##......
..+...####...... ........#.......
..++..####...... ................
................ ................
same as the copy: True | pixel sum: 43850 43850
27.5 When it pays, and when it does not
Divide and conquer 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 instead of , and a merge sort built that way is no faster than insertion sort. On very small inputs, the calls and copies cost more than they save: at merge sort is only about twice as fast. Real sorting functions, Python’s sorted among them, 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).
27.6 Exercises
Exercise 27.1 ★
Merge and step by step. How many comparisons?
Solution
Solution of Exercise 27.1.
: out . : . : . : . : . : . The first list is empty, and is copied. The result is , after comparisons.
Exercise 27.2 ★
What are the smallest and the largest numbers of comparisons when merging a list of elements with one of ? Give an example of each.
Solution
Solution of Exercise 27.2.
At least : each comparison outputs one element, and a list must run out; with needs exactly . At most : the last element is always copied without comparing; with needs .
Exercise 27.3 ★
Draw the splits and the merges of merge_sort on .
Solution
Solution of Exercise 27.3.
Splits: and ; then and , and ; then , , , . Merges: and ; then and ; then .
Exercise 27.4 ★
List the multiplications power(x, 13) makes. How many are there?
Solution
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), , with no multiplication. Then (two), (one), (two): five multiplications.
Exercise 27.5 ★
Write merge_desc(a, b), which merges two lists sorted in decreasing order.
Solution
Solution of Exercise 27.5.
The 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
Solution of Exercise 27.6.
[1, 2, 3]: when b runs out, and 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 holds the Fibonacci number in its top right corner. Write fib(n) with fast exponentiation of matrices.
Solution
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 matrix products, against additions in a loop, and the recursion of chapter 22 would never finish.
Exercise 27.8 ★★
Prove by induction on that merge sort makes at most comparisons on a list of elements.
Solution
Solution of Exercise 27.8.
Let be the largest number of comparisons on elements. . For , the two halves have elements each, so at most comparisons each, and merging them makes at most . If , then .
Exercise 27.9 ★★
Turn the grid of letters with rows ab, cd a quarter clockwise. Then turn the grid with rows abcd, efgh, ijkl, mnop by quadrants, giving the grid after each of the two stages.
Solution
Solution of Exercise 27.9.
ab, cd becomes ca, db. For the 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
Solution of Exercise 27.10.
mid is : 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 .
Exercise 27.11 ★★
Write a merge sort without recursion: start from runs of one element, and merge the runs two by two until one is left.
Solution
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): passes at most, each merging all elements, the same work as the recursive version.
Exercise 27.12 ★★★
Prove that power(x, n) makes at most multiplications for , and exactly (number of binary digits of ) (number of digits ).
Solution
Solution of Exercise 27.12.
Write for the number of binary digits of and for its number of digits ; claim . For : . For , is without its last binary digit: and . The call makes multiplications more than the call on , so by induction . Since and , . For , written with digits of which are : , 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
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 to .
Exercise 27.14 ★★★
Show that for , merge sort makes at least comparisons on every input: whatever the order, its count is within a factor of .
Solution
Solution of Exercise 27.14.
A merge of two lists of elements each makes at least comparisons: each comparison outputs one element, and the loop stops only when one list is empty. At the level where blocks of elements are merged in pairs, there are merges of at least comparisons: at least per level, and there are levels. So the count lies between and , 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. Test it against the sums of all blocks.
Solution
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 : . The tests compare with the sums of all blocks on 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 with . The program counts inversions by trying every pair, and by a merge sort that counts them on the way.
"""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]
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")
$ 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
"""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")
$ 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
Part I — Rankings.
- In the example of five, which pairs do the judges order differently?
- What list does
comparegive for two identical rankings, and how many inversions? For two opposite rankings of items? - Why is the number of inversions at most ?
- Two random rankings: what share of the pairs would you guess to be inverted? Compare with the output.
Part II — Brute force.
- How many pairs does
inversions_bruteexamine for items? - From the measured times, by how much does the brute-force time grow when doubles? Why?
- Estimate its time for from the time at .
Part III — Counting while merging.
- Split the inversions of a list into three kinds, by where their two positions lie.
- Which two kinds do the recursive calls count?
- Why can the third kind be counted on the two sorted halves, although sorting changed the positions?
- Explain the loop over
right: why islen(left) - ithe number of inversions withb? - Why does
inever go back, and what does that make the cost of the loop? - Prove, by induction on the length, that
sort_countreturns the number of inversions.
Part IV — Cost and speed.
- How many comparisons does
sort_countmake, roughly, for ? - Read the measured ratio of the two methods at each . How does it grow?
- From your estimate of question 7, what would the ratio be at ?
- From to , compare the growth of the measured ratio with that of .
- The brute-force method is still useful. For what?
- The tests check the count at against no brute force. What do they check instead?
- State the result: the inversions between the two rankings of , and the measured ratio at .
Solution
Solution of Problem 27.1.
1. compare gives . The inverted pairs: Ada and Ben; Cleo and Eli; Dev and Eli.
2. Identical rankings give , with no inversion. Opposite rankings give : every pair is inverted, inversions.
3. An inversion is a pair of positions, and there are pairs.
4. About half: in a random ranking each pair is as likely in one order as in the other. The output gives .
5. : every pair.
6. About four times: the printed run gives , , and seconds (another run gives slightly different times). Doubling about quadruples the number of pairs.
7. 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.
13. For a list of or element, no pair: . 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.
14. The merges make at most comparisons and the counting loops about more: about , against pairs for brute force.
15. , , , in the printed run: it about doubles each time doubles.
16. About , that is, about .
17. goes from about to about , a factor of about ; the measured ratio goes from to , a factor of about . 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 , and keep the count at fixed to the value printed, so that any later change to the code that alters it is noticed.
20. The two random rankings of items differ on of their pairs (); at , counting by merging was about times faster than trying every pair ( in the printed run), and about times is expected at .