Exercise 17 of 30 · intermediate · recursion · linearithmic · merge sort · recurrences

Two halves plus linear work

The code

def solve(a):
    if len(a) <= 1: return a
    left = solve(a[:len(a)//2])
    right = solve(a[len(a)//2:])
    return merge(left, right)   # linear

Solve T(n) = 2T(n/2) + Θ(n).

Count: merge comparisons (reversed input).

Measured counts

010k20k20004000ncount
Measured
Table
ncount
812
1632
3280
64192
128448
2561,024
5122,304
10245,120
204811,264
409624,576

Try to name the class from the shape before opening the answer.

Show the answer and derivation
Time
Θ(n log n)
Extra space
Θ(n)
  1. Draw the recursion tree: level k has 2ᵏ subproblems of size n/2ᵏ.
  2. Each level does Θ(n) work in total.
  3. There are ⌈log₂ n⌉ levels: Θ(n log n). This is merge sort.

Common mistake: Answering Θ(n) because each call does "only" linear work. The linear work happens on every level.

Check: measured count ÷ (n log n) settles near 0.500 for large n.