Sub topic 6
Deriving O(n log n) from the Recurrence
This chapter assumes you can read Python, follow a recursive function through its calls, and use Big-O notation. It also assumes you have the top-down merge_sort and merge functions from the earlier chapters. The goal here is to show why that code runs in O(n log n) time on every input, using three methods: the recursion tree, unrolling the recurrence, and the master theorem. After that, the chapter checks the result by counting comparisons.
Writing Down the Recurrence
A recurrence is an equation that defines a function in terms of its own values on smaller inputs. To get one for merge sort, look at what a single call on n elements does:
- If n ≤ 1, it returns right away. That costs a constant amount of work.
- Otherwise it splits the list at the midpoint. In the Python version, the slices
items[:mid]anditems[mid:]copy n elements in total, so this step costs O(n). - It makes two recursive calls, each on about n/2 elements.
- It merges the two sorted halves. The merge does at most n − 1 comparisons and appends exactly n elements, so it is also O(n).
If a constant c bounds the work per element in steps 2 and 4, then:
- T(1) = c
- T(n) = 2T(n/2) + cn, for n > 1
For now, assume n is a power of two so that every split is exact. A later section removes this assumption.
Method 1: The Recursion Tree
A recursion tree draws every call as a node and labels each node with the work it does outside its recursive calls. The total running time is the sum of all the labels.
Count level by level:
| Level | Number of calls | Size of each call | Work per call | Work for the level |
|---|---|---|---|---|
| 0 | 1 | n | cn | cn |
| 1 | 2 | n/2 | cn/2 | cn |
| 2 | 4 | n/4 | cn/4 | cn |
| k | 2^k | n/2^k | cn/2^k | cn |
| log2 n | n | 1 | c | cn |
Two facts give the answer:
- Every level costs cn. The number of calls doubles from one level to the next while each call's size halves, so the two changes cancel. Put another way, every element of the input sits in exactly one subproblem per level, and each element costs constant work at that level.
- There are log2 n + 1 levels. The size reaches 1 when n/2^k = 1, which means k = log2 n.
Total: cn(log2 n + 1) = cn log2 n + cn, which is Θ(n log n).
Method 2: Unrolling the Recurrence
Unrolling means substituting the recurrence into itself until you can see a pattern. Start with T(n) = 2T(n/2) + cn and expand T(n/2) = 2T(n/4) + cn/2:
- T(n) = 2[2T(n/4) + cn/2] + cn = 4T(n/4) + 2cn
- T(n) = 4[2T(n/8) + cn/4] + 2cn = 8T(n/8) + 3cn
After k substitutions the pattern is:
T(n) = 2^k · T(n/2^k) + k·cn
Stop when the argument reaches the base case. n/2^k = 1 gives k = log2 n and 2^k = n:
T(n) = n · T(1) + cn log2 n = cn + cn log2 n
The result matches the recursion tree, as it should, since unrolling is the same tree summed one level at a time. To be rigorous you would prove the pattern by induction on k. Plugging the closed form back into the recurrence is a quick check: 2[c(n/2) + c(n/2)log2(n/2)] + cn = cn + cn(log2 n − 1) + cn = cn + cn log2 n.
Method 3: The Master Theorem
The master theorem solves recurrences of the form T(n) = aT(n/b) + f(n). It compares f(n) with n^(log_b a):
| Case | Condition | Result |
|---|---|---|
| 1 | f(n) grows polynomially slower than n^(log_b a) | Θ(n^(log_b a)) |
| 2 | f(n) = Θ(n^(log_b a)) | Θ(n^(log_b a) · log n) |
| 3 | f(n) grows polynomially faster, and a regularity condition holds | Θ(f(n)) |
For merge sort, a = 2, b = 2, and f(n) = cn. Then n^(log_2 2) = n¹ = n, which matches f(n). That is case 2, so T(n) = Θ(n log n).
Case 2 is the balanced case, where every level of the tree does the same amount of work. In case 1 the leaves dominate the total, and in case 3 the root does.
When n Is Not a Power of Two
Real inputs have arbitrary lengths. With mid = len(items) // 2, the exact recurrence is:
T(n) = T(⌊n/2⌋) + T(⌈n/2⌉) + cn
Two arguments show that this does not change the answer:
- Monotonicity. T is non-decreasing in n, because more elements never means less work. Let N be the next power of two at or above n, so N < 2n. Then T(n) ≤ T(N) = cN log2 N + cN < 2cn(log2 n + 1) + 2cn, which is still O(n log n).
- Tree depth. The halves differ in size by at most one, so the tree has ⌈log2 n⌉ + 1 levels, and each level still touches each element at most once. The total is at most cn(⌈log2 n⌉ + 1).
The matching lower bound holds in the same way, so the running time is Θ(n log n) for every n.
Best, Worst, and Average Case Are the Same Order
Quicksort's running time depends on its pivot choices, and insertion sort's depends on how sorted the input is. Merge sort's splits are fixed by position, so the shape of the tree never depends on the data. Only the number of comparisons inside each merge changes:
- Fewest comparisons. Merging halves of sizes m and m takes m comparisons when one half is used up first. This happens, for example, when the input is already sorted.
- Most comparisons. The merge takes 2m − 1 comparisons when the two halves interleave all the way to the end.
So every merge does between half and all of its maximum work, and every input costs Θ(n log n). For n a power of two, the comparison count of plain merge sort is exactly (n/2)log2 n on sorted input. In the worst case it is n log2 n − n + 1.
Checking the Analysis by Counting Comparisons
The script below adds a comparison counter to merge sort and compares the count with n log2 n on random, sorted, and reversed inputs.
import math
import random
def merge_count(left, right):
result = []
i = j = 0
comparisons = 0
while i < len(left) and j < len(right):
comparisons += 1
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result, comparisons
def merge_sort_count(items):
if len(items) <= 1:
return list(items), 0
mid = len(items) // 2
left, c_left = merge_sort_count(items[:mid])
right, c_right = merge_sort_count(items[mid:])
merged, c_merge = merge_count(left, right)
return merged, c_left + c_right + c_merge
random.seed(42)
print(f"{'n':>7} {'n log2 n':>10} {'random':>9} {'sorted':>9} {'reversed':>9}")
for n in [16, 256, 1024, 4096, 65536]:
data = list(range(n))
shuffled = random.sample(data, n)
_, c_random = merge_sort_count(shuffled)
_, c_sorted = merge_sort_count(data)
_, c_reversed = merge_sort_count(data[::-1])
print(f"{n:>7} {round(n * math.log2(n)):>10} "
f"{c_random:>9} {c_sorted:>9} {c_reversed:>9}")Things to look for in the output:
- The sorted and reversed columns are exactly (n/2)log2 n. For n = 1024 that is 5120. Reversed input is also a best case, because every element of the right half is smaller than every element of the left half, so the right half runs out first.
- The random column sits just below the worst case n log2 n − n + 1, which is 9217 for n = 1024.
- When n grows by a factor of 16, from 4096 to 65536, every column grows by a factor of a little over 21. That is 16 × (16/12), the factor you expect from n log n.
Merge Sort Meets the Lower Bound
Any sort that only compares elements must do Ω(n log n) comparisons in the worst case. A comparison sort has to tell apart all n! orderings of the input, and each comparison has only two outcomes. That forces at least log2(n!) comparisons, and log2(n!) is about n log2 n − 1.44n. Merge sort's worst case of n log2 n − n + 1 comes within a linear term of this bound. No comparison sort can beat it by more than a constant factor.
Exercises
Exercise
A three-way merge sort splits the list into thirds, sorts each third recursively, and merges the three sorted runs in O(n) time. Write its recurrence and solve it.
Show answer
T(n) = 3T(n/3) + cn. With a = 3 and b = 3, n^(log_3 3) = n matches f(n), so case 2 of the master theorem gives Θ(n log n). The tree has log3 n levels instead of log2 n, which changes only the constant factor.
Exercise
A buggy merge sort splits the list into one element and the remaining n − 1 elements, but still merges in linear time. What is its running time?
Show answer
T(n) = T(n − 1) + T(1) + cn. Unrolling gives cn + c(n − 1) + ... + c·2 plus the base-case costs, which is Θ(n²). The tree is n levels deep instead of log n, so balanced splitting is what produces the log factor.
Exercise
Suppose the merge step were accidentally written to take Θ(n²) time. Solve T(n) = 2T(n/2) + cn².
Show answer
Level k does 2^k · c(n/2^k)² = cn²/2^k work, so the level costs form a geometric series that the root dominates. The total is below 2cn², which is Θ(n²). This is case 3 of the master theorem.
Exercise
How many comparisons does the plain merge sort from this chapter make on the already-sorted list [1, 2, ..., 16]?
Show answer
32. On sorted input, each merge of two halves of size m takes m comparisons, so each of the log2 16 = 4 levels costs n/2 = 8 comparisons. The total is (16/2) × 4 = 32.