Sub topic 1
What Divide and Conquer Means: Divide, Conquer, Combine
Prerequisites
This chapter assumes you can write and trace recursive functions in Python, read Big-O notation, and follow a proof by induction.
The Three Steps
A divide-and-conquer algorithm has three steps:
- Divide the input into smaller subproblems of the same kind.
- Conquer each subproblem by solving it recursively.
- Combine the subproblem results into the answer for the whole input.
The following function finds the largest element of a list in this way:
def max_dc(a, lo, hi):
# Largest element of the non-empty slice a[lo:hi]
if hi - lo == 1: # base case
return a[lo]
mid = (lo + hi) // 2 # divide
left = max_dc(a, lo, mid) # conquer
right = max_dc(a, mid, hi) # conquer
return max(left, right) # combine
print(max_dc([4, 9, 2, 7, 5], 0, 5)) # 9Base Cases and Termination
The base case is an input small enough to answer directly. Recursion terminates only when two things hold. Every recursive call must receive a strictly smaller input, and every chain of shrinking inputs must reach a base case. In max_dc, a slice with at least two elements splits into two non-empty halves, and each half is smaller than the slice, so the sizes eventually reach 1.
Proving Correctness by Induction
Use strong induction on the size n = hi − lo. When n = 1, the function returns the only element, which is the maximum. For n > 1, assume the function is correct on every smaller size. Both halves are smaller, so left and right are the correct maxima of their halves. The largest element of the whole slice lies in one of the halves, so max(left, right) is correct.
Recurrences
A recurrence gives the running time T(n) in terms of the running time on smaller inputs. In max_dc, the function makes two calls on inputs of size n/2 and does constant work besides those calls:
T(n) = 2T(n/2) + O(1), with T(1) = O(1).
Recursion Trees
A recursion tree draws each call as a node, labeled with the work that call does outside its recursive calls. To get the total running time, add up the work at each level of the tree, then add the levels together.
Level i has 2^i nodes that each cost c. The tree has log₂ n + 1 levels, so the total is c(1 + 2 + 4 + … + n) < 2cn. The running time is therefore O(n).
Exercise
Use a recursion tree to solve T(n) = 2T(n/2) + n, with T(1) = 1.
Show answer
Level i has 2^i nodes, and each node costs n/2^i, so every level costs n in total. The tree has log₂ n + 1 levels, so T(n) = n(log₂ n + 1) = O(n log n).