Sub topic 2
The Master Theorem and Its Three Cases
This chapter assumes you can write a recurrence such as T(n) = 2T(n/2) + O(n) and can read Big-O notation. It uses the master theorem to analyze four classic algorithms.
The Master Theorem
Many divide-and-conquer recurrences take the form T(n) = aT(n/b) + f(n). Here a is the number of subproblems, n/b is the size of each one, and f(n) is the cost of dividing the input and combining the results. To solve the recurrence, compare f(n) with n^(log_b a). That quantity is the total work done at the leaves of the recursion tree.
| Case | Condition | Result |
|---|---|---|
| 1 | f(n) grows polynomially slower than n^(log_b a) | T(n) = Θ(n^(log_b a)) |
| 2 | f(n) = Θ(n^(log_b a)) | T(n) = Θ(n^(log_b a) log n) |
| 3 | f(n) grows polynomially faster, and the regularity condition holds | T(n) = Θ(f(n)) |
Binary Search
Binary search compares the target with the middle element and throws away the half that cannot contain it. That gives T(n) = T(n/2) + O(1). Here a = 1 and b = 2, so n^(log_2 1) = 1, which matches f(n). Case 2 applies, and the result is O(log n).
Merge Sort
Merge sort splits the list in half, sorts each half, and merges the two halves in linear time. The recurrence is T(n) = 2T(n/2) + O(n). Since n^(log_2 2) = n matches f(n), case 2 gives O(n log n).
Quicksort
Quicksort does its main work before it recurses. It partitions the list around a pivot, and once both sides are sorted, no combine step is needed. When the pivots split the list evenly, the recurrence matches merge sort's and gives O(n log n). When the pivots are always the smallest or largest element, the recurrence becomes T(n) = T(n − 1) + O(n), which is O(n²). Choosing the pivot at random makes the expected time O(n log n).
Counting Inversions
An inversion is a pair of positions i < j where a[i] > a[j]. During the merge, each time an element is taken from the right half, it forms an inversion with every element still waiting in the left half. Counting those pairs adds only constant work per step, so the algorithm keeps merge sort's O(n log n) running time.
def sort_and_count(a):
if len(a) <= 1:
return a, 0
mid = len(a) // 2
left, inv_left = sort_and_count(a[:mid])
right, inv_right = sort_and_count(a[mid:])
out = []
i = j = 0
split_inv = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
split_inv += len(left) - i
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out, inv_left + inv_right + split_inv
print(sort_and_count([2, 4, 1, 3, 5])[1]) # 3Exercise
Solve T(n) = 4T(n/2) + O(n) with the master theorem.
Show answer
Here n^(log_2 4) = n², which grows polynomially faster than f(n) = n. Case 1 applies, so T(n) = Θ(n²).
Exercise
Why does the merge step use <= instead of < when counting inversions?
Show answer
Equal elements do not form an inversion. Using <= takes the left element first, so equal pairs are never counted.