Sub topic 5
The Master Theorem
Prerequisites and the Recurrence Shape
Assume you know recursion, logarithms, asymptotic notation, and simple summations. The Master theorem is a shortcut for solving many divide-and-conquer recurrences.
A recurrence describes the running time of a recursive algorithm. The standard form is:
\[ T(n) = aT(n/b) + f(n) \]
Here:
- \(n\) is the input size.
- \(a\) is the number of recursive subproblems.
- Each subproblem has size \(n/b\).
- \(f(n)\) is the work outside the recursive calls.
- \(a\), \(b\), and \(n\) are positive, with \(b > 1\).
The important comparison is between \(f(n)\) and:
\[ n^{\log_b a} \]
This quantity represents the total work contributed by the recursive tree’s leaves.
The Three Cases
Let \(p = \log_b a\).
| Condition on \(f(n)\) | Result for \(T(n)\) |
|---|---|
| \(f(n)=O(n^{p-\epsilon})\) for some \(\epsilon>0\) | \(\Theta(n^p)\) |
| \(f(n)=\Theta(n^p\log^k n)\) for \(k\geq 0\) | \(\Theta(n^p\log^{k+1}n)\) |
| \(f(n)=\Omega(n^{p+\epsilon})\), with a regularity condition | \(\Theta(f(n))\) |
In Case 1, recursive work dominates. In Case 2, the recursive levels and the outside work contribute comparable amounts. In Case 3, the work done at each node dominates the recursive contribution.
The regularity condition in Case 3 usually appears as:
\[ af(n/b) \leq cf(n) \]
for some constant \(c<1\). It prevents \(f(n)\) from fluctuating too much between levels.
Worked Examples
Binary Search
Binary search makes one recursive call on half the input and performs constant extra work:
\[ T(n)=T(n/2)+\Theta(1) \]
Thus \(a=1\), \(b=2\), and \(p=\log_2 1=0\). Since \(f(n)=\Theta(n^0)\), this is Case 2 with \(k=0\):
\[ T(n)=\Theta(\log n) \]
Merge Sort
Merge sort makes two calls on halves and spends linear time merging:
\[ T(n)=2T(n/2)+\Theta(n) \]
Here \(a=2\), \(b=2\), and \(p=\log_2 2=1\). The outside work matches \(n^p=n\), so Case 2 gives:
\[ T(n)=\Theta(n\log n) \]
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
result = []
i = j = 0
while i < len(left) and j < len(right):
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 resultExercise
What is the complexity of T(n) = 4T(n/2) + Theta(n^2)?
Show answer
Since log_2(4)=2 and f(n)=Theta(n^2), this is Case 2. The complexity is Theta(n^2 log n).