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) # linearSolve T(n) = 2T(n/2) + Θ(n).
Count: merge comparisons (reversed input).
Measured counts
Table
| n | count |
|---|---|
| 8 | 12 |
| 16 | 32 |
| 32 | 80 |
| 64 | 192 |
| 128 | 448 |
| 256 | 1,024 |
| 512 | 2,304 |
| 1024 | 5,120 |
| 2048 | 11,264 |
| 4096 | 24,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)
- Draw the recursion tree: level k has 2ᵏ subproblems of size n/2ᵏ.
- Each level does Θ(n) work in total.
- 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.