divide and conquer
Chapter eighteen covers this method and includes two lower bound proofs, one for the minmax problem and one for sorting The method gives you an algorithm The proof tells you when to stop trying to beat it
The three moves
- divide the input into smaller instances of the same problem
- conquer by solving those instances recursively
- combine the results
Most mistakes are in the combine step People write the recursion, admire it, and forget that the answers have to be joined That is like assembling a desk and throwing away the screws
Merge sort again
std::vector<int> merge_sort(const std::vector<int> &items) {
if (items.size() <= 1) return items;
auto mid = items.size() / 2;
auto left = merge_sort(std::vector<int>(items.begin(), items.begin() + mid));
auto right = merge_sort(std::vector<int>(items.begin() + mid, items.end()));
return merge(left, right);
}
The split is trivial
The base case is trivial
merge carries the work
Binary search as a relative
Binary search divides and discards It does not combine Same instinct, different shape That is why it is treated separately in the asymptotic chapter
Minmax
Finding the minimum and maximum together is a classic exercise
A naive scan uses about 2n comparisons
Pairing elements first, then comparing winners and losers, reduces that
The lower bound proof says how far down you can go That is not trivia It is the difference between “seems faster” and “cannot do better”
Recurrence
Work usually looks like T(n) = 2T(n/2) + f(n)
The f(n) is the combine cost
If combine is linear, the total is n log n
If combine is constant, the total is linear
Write that line before you code It tells you what to expect and stops you optimising the wrong half
When it fits
- the problem shrinks cleanly
- subproblems do not overlap
- combining is cheaper than recomputing
If subproblems overlap, this is not the right tool That is dynamic programming territory
Mistakes
- forgetting the base case
- splitting unevenly and losing the guarantee
- mutating shared state across recursive branches
- assuming recursion depth is free
Exercises
- Write the recurrence for merge sort and explain each term
- Implement minmax with pairing and count comparisons
- Explain why binary search is not a full divide and conquer algorithm
- Find one recursive function in your code and identify its combine step
What to remember
Divide and conquer buys structure The proof tells you the floor
Posted