Recurrences: Towers of Hanoi and Merge Sort
A recurrence defines a sequence in terms of its earlier values. Recursive algorithms produce them naturally: the cost of solving a problem of size is the cost of the smaller subproblems plus the work to combine them. This lesson solves two classic recurrences by guess and verify and by plug and chug (unrolling), then checks them in code.
Towers of Hanoi
Move a stack of discs from peg A to peg C, one disc at a time, never placing a larger disc on a smaller one. To move discs: move the top to the spare peg, move the largest disc, move the back on top. If is the number of moves,
Guess. The values suggest .
Verify by induction. . If , then .
The recursive algorithm is optimal: the largest disc must move at least once, and before it moves, the other discs must all sit on the third peg, which takes at least moves; afterwards they must move back on top. So no method uses fewer than moves.
def hanoi(n, src="A", dst="C", spare="B", moves=None):
if moves is None:
moves = []
if n > 0:
hanoi(n - 1, src, spare, dst, moves)
moves.append((n, src, dst))
hanoi(n - 1, spare, dst, src, moves)
return moves
print(hanoi(3))
print([len(hanoi(n)) for n in range(11)])
print("64 discs at one move per second:", (2 ** 64 - 1) / (3600 * 24 * 365.25) / 1e9, "billion years")[(1, 'A', 'C'), (2, 'A', 'B'), (1, 'C', 'B'), (3, 'A', 'C'), (1, 'B', 'A'), (2, 'B', 'C'), (1, 'A', 'C')]
[0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]
64 discs at one move per second: 584.5420460906263 billion years
Plug and chug
Unroll the recurrence until a pattern appears, then sum:
The unrolled form must still be proved (induction), but it often finds the answer when guessing fails.
Merge sort
Merge sort splits the list in halves, sorts each recursively, and merges them with at most comparisons. For a power of 2, the worst-case number of comparisons is
Plug and chug with :
So merge sort makes about comparisons, matching the lower bound from Stirling's formula up to a lower-order term.
import math
def merge_sort(a, counter):
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = merge_sort(a[:mid], counter), merge_sort(a[mid:], counter)
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
counter[0] += 1
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
return out + left[i:] + right[j:]
for k in range(1, 11):
n = 2 ** k
T = lambda m: 0 if m == 1 else 2 * T(m // 2) + m - 1
c = [0]
merge_sort(list(range(n))[::-1], c)
print(f"n={n:5d} T(n)={T(n):6d} n log2 n - n + 1={int(n * math.log2(n) - n + 1):6d} reversed input used {c[0]}")n= 2 T(n)= 1 n log2 n - n + 1= 1 reversed input used 1
n= 4 T(n)= 5 n log2 n - n + 1= 5 reversed input used 4
n= 8 T(n)= 17 n log2 n - n + 1= 17 reversed input used 12
n= 16 T(n)= 49 n log2 n - n + 1= 49 reversed input used 32
n= 32 T(n)= 129 n log2 n - n + 1= 129 reversed input used 80
n= 64 T(n)= 321 n log2 n - n + 1= 321 reversed input used 192
n= 128 T(n)= 769 n log2 n - n + 1= 769 reversed input used 448
n= 256 T(n)= 1793 n log2 n - n + 1= 1793 reversed input used 1024
n= 512 T(n)= 4097 n log2 n - n + 1= 4097 reversed input used 2304
n= 1024 T(n)= 9217 n log2 n - n + 1= 9217 reversed input used 5120
A reversed input is the best case for merging (one side runs out early, comparisons); the formula is the worst case.
In software
Every recursive function's cost is a recurrence: binary search gives ; naive Fibonacci gives exponential time; Karatsuba multiplication gives . The Divide-and-Conquer Recurrences lesson gives a formula for the whole family.
Exercises
Exercise 1: Solve by guess and verify
Solve , .
Answer
.
Solution
Values suggest . Induction: ; .
Exercise 2: Plug and chug
Solve , .
Answer
.
Solution
Unrolling gives , the triangular number.
Exercise 3: Binary search (code)
Binary search on elements does comparisons in the worst case, . Compute for and compare with .
Answer
They are equal for every .
Solution
import math
T = lambda n: 1 if n == 1 else T(n // 2) + 1
print([T(n) for n in range(1, 21)])
print(all(T(n) == math.floor(math.log2(n)) + 1 for n in range(1, 2000)))[1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5]
True
Test yourself
How many moves does the Towers of Hanoi puzzle need for 5 discs?
- 10
- 25
- 31
- 32
What does , solve to for ?
After guessing a solution with plug and chug, what should you still do?
- Nothing
- Prove it, for example by induction
- Run it once
- Differentiate it