TExcelTAD
Home › Discrete Mathematics › Recurrences: Towers of Hanoi and Merge Sort

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 nn 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 nn discs from peg A to peg C, one disc at a time, never placing a larger disc on a smaller one. To move nn discs: move the top n−1n - 1 to the spare peg, move the largest disc, move the n−1n - 1 back on top. If TnT_n is the number of moves,

T0=0,Tn=2Tn−1+1T_0 = 0, \qquad T_n = 2T_{n-1} + 1

Guess. The values 0,1,3,7,15,310, 1, 3, 7, 15, 31 suggest Tn=2n−1T_n = 2^n - 1.

Verify by induction. T0=20−1=0T_0 = 2^0 - 1 = 0. If Tn−1=2n−1−1T_{n-1} = 2^{n-1} - 1, then Tn=2(2n−1−1)+1=2n−1T_n = 2(2^{n-1} - 1) + 1 = 2^n - 1. ■\blacksquare

The recursive algorithm is optimal: the largest disc must move at least once, and before it moves, the other n−1n - 1 discs must all sit on the third peg, which takes at least Tn−1T_{n-1} moves; afterwards they must move back on top. So no method uses fewer than 2Tn−1+12T_{n-1} + 1 moves.

python · try it yourself
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:

Tn=1+2Tn−1=1+2+4Tn−2=1+2+4+8Tn−3=1+2+⋯+2k−1+2kTn−k=2n−1+2nT0=2n−1at k=n\begin{aligned} T_n &= 1 + 2T_{n-1} \\ &= 1 + 2 + 4T_{n-2} \\ &= 1 + 2 + 4 + 8T_{n-3} \\ &= 1 + 2 + \cdots + 2^{k-1} + 2^k T_{n-k} \\ &= 2^n - 1 + 2^n T_0 = 2^n - 1 && \text{at } k = n \end{aligned}

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 n−1n - 1 comparisons. For nn a power of 2, the worst-case number of comparisons is

T(1)=0,T(n)=2T(n/2)+n−1T(1) = 0, \qquad T(n) = 2T(n/2) + n - 1

Plug and chug with n=2kn = 2^k:

T(n)=(n−1)+2T(n/2)=(n−1)+(n−2)+4T(n/4)=(n−1)+(n−2)+(n−4)+8T(n/8)=kn−(1+2+⋯+2k−1)+2kT(1)=nlog⁡2n−n+1\begin{aligned} T(n) &= (n - 1) + 2T(n/2) \\ &= (n - 1) + (n - 2) + 4T(n/4) \\ &= (n - 1) + (n - 2) + (n - 4) + 8T(n/8) \\ &= kn - (1 + 2 + \cdots + 2^{k-1}) + 2^k T(1) = n \log_2 n - n + 1 \end{aligned}

So merge sort makes about nlog⁡2nn \log_2 n comparisons, matching the lower bound from Stirling's formula up to a lower-order term.

python · try it yourself
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, n2log⁡2n\frac{n}{2}\log_2 n comparisons); the formula T(n)T(n) is the worst case.

In software

Every recursive function's cost is a recurrence: binary search T(n)=T(n/2)+1T(n) = T(n/2) + 1 gives log⁡2n\log_2 n; naive Fibonacci T(n)=T(n−1)+T(n−2)+1T(n) = T(n-1) + T(n-2) + 1 gives exponential time; Karatsuba multiplication T(n)=3T(n/2)+O(n)T(n) = 3T(n/2) + O(n) gives n1.585n^{1.585}. The Divide-and-Conquer Recurrences lesson gives a formula for the whole family.

Exercises

Exercise 1: Solve by guess and verify

Solve S0=1S_0 = 1, Sn=3Sn−1S_n = 3S_{n-1}.

Answer

Sn=3nS_n = 3^n.

Solution

Values 1,3,9,271, 3, 9, 27 suggest 3n3^n. Induction: S0=30S_0 = 3^0; Sn=3⋅3n−1=3nS_n = 3 \cdot 3^{n-1} = 3^n.

Exercise 2: Plug and chug

Solve A0=0A_0 = 0, An=An−1+nA_n = A_{n-1} + n.

Answer

An=n(n+1)2A_n = \frac{n(n+1)}{2}.

Solution

Unrolling gives An=n+(n−1)+⋯+1+A0A_n = n + (n - 1) + \cdots + 1 + A_0, the triangular number.

Exercise 3: Binary search (code)

Binary search on nn elements does T(n)=T(⌊n/2⌋)+1T(n) = T(\lfloor n/2 \rfloor) + 1 comparisons in the worst case, T(1)=1T(1) = 1. Compute T(n)T(n) for n=1,…,20n = 1, \ldots, 20 and compare with ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1.

Answer

They are equal for every nn.

Solution
python · try it yourself
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?

  1. 10
  2. 25
  3. 31
  4. 32

What does T(n)=2T(n/2)+n−1T(n) = 2T(n/2) + n - 1, T(1)=0T(1) = 0 solve to for n=2kn = 2^k?

  1. n2n^2
  2. nlog⁡2n−n+1n \log_2 n - n + 1
  3. 2n2^n
  4. n−1n - 1

After guessing a solution with plug and chug, what should you still do?

  1. Nothing
  2. Prove it, for example by induction
  3. Run it once
  4. Differentiate it