Divide and Conquer: Merge Sort, Binary Search and Fast Powers
Divide and conquer is a way of designing algorithms in three steps: split the problem into smaller problems of the same kind, solve each of them (usually by recursion), and combine their answers into an answer for the whole. Many of the algorithms you meet early, including merge sort and binary search, are this pattern, and their running times all come from the same kind of recurrence. This guide walks through three shapes of the pattern, shows the recurrence each produces, and explains when splitting a problem does not help.
Divide, conquer, combine
- Divide the input into a subproblems, each a fraction 1/b of the size.
- Conquer each subproblem recursively. When a subproblem is small enough, solve it directly: that is the base case.
- Combine the sub-answers into the answer.
If dividing and combining together cost f(n), the running time is T(n) = a T(n/b) + f(n). The design question is always the same: can you make a small, or make f(n) cheap, without losing correctness? The master theorem then turns the recurrence into a bound.
Shape 1: merge sort, two halves and a linear combine
- Divide: split the list at the middle. Constant work if you track indices, linear if you copy slices.
- Conquer: sort each half recursively.
- Combine: merge the two sorted halves by repeatedly taking the smaller front item. Linear work.
Recurrence: T(n) = 2T(n/2) + O(n). Every level of the recursion tree does about n work in total and there are about log2 n levels, so merge sort is Theta(n log n) in every case. All the cleverness is in the combine step: merging two sorted lists is much cheaper than sorting their union from scratch. Merge sort and its partner quicksort, which puts the work in the divide step instead, have their own guide with code.
Shape 2: binary search, one half and nothing to combine
- Divide: compare the target with the middle item of a sorted list.
- Conquer: search only the half that can contain the target. The other half is discarded, not solved.
- Combine: nothing; the answer from the half is the answer.
Recurrence: T(n) = T(n/2) + O(1), which is Theta(log n) in the worst case. Binary search shows that "conquer" can mean solving just one subproblem, and that is where its speed comes from: each step throws half the input away. Some authors call this variant "decrease and conquer".
Shape 3: fast exponentiation, one half and a small combine
To compute x^n, the obvious loop multiplies by x a total of n - 1 times. Divide and conquer does much better using x^n = (x^(n/2))^2 when n is even, and x^n = (x^((n-1)/2))^2 x x when n is odd.
- Divide: halve the exponent (integer division).
- Conquer: compute x^(n // 2) recursively, once.
- Combine: square it, and multiply by x once more if n is odd. One or two multiplications.
Recurrence for the number of multiplications: M(n) = M(n/2) + O(1), so M(n) is O(log n). The key detail is that the half-size result is computed once and squared, not computed twice; calling the function twice on n // 2 would give M(n) = 2M(n/2) + O(1), which is back to linear.
Examples use Python 3.10 or later and only the standard library. This version returns the power and counts multiplications.
def power(x, n):
"""Return (x**n, multiplications used) for an integer n >= 0."""
if n == 0:
return 1, 0
half, count = power(x, n // 2)
result = half * half
count += 1
if n % 2 == 1:
result *= x
count += 1
return result, count
for n in [10, 100, 1000]:
value, mults = power(3, n)
print(n, mults, value == 3 ** n, len(str(value)), "digits")
Output (n, multiplications, check against the built-in operator, size of the result):
10 6 True 5 digits
100 10 True 48 digits
1000 16 True 478 digits
Computing 3^1000 takes 16 multiplications instead of 999. The count is one squaring per binary digit of n (10 digits for 1000) plus one extra multiplication per 1 bit (six for 1000, which is 1111101000 in binary). This simple version also spends one squaring on 1 x 1 at the bottom of the recursion; a tidier version starts from n = 1 and saves it.
A caution about what is being counted: 3^1000 has 478 digits, and multiplying large integers is not a constant-time operation. Fast exponentiation does O(log n) multiplications; its running time also depends on how expensive each multiplication is. When the numbers are kept small by working modulo m, as in pow(x, n, m), every multiplication is on bounded numbers and the whole computation takes O(log n) arithmetic steps. Python's built-in three-argument pow computes exactly that.
Reading the three shapes
| Algorithm | a | b | outside work | recurrence | bound |
|---|---|---|---|---|---|
| merge sort | 2 | 2 | O(n) | T(n) = 2T(n/2) + O(n) | Theta(n log n) |
| binary search | 1 | 2 | O(1) | T(n) = T(n/2) + O(1) | Theta(log n) |
| fast exponentiation (multiplications) | 1 | 2 | O(1) | M(n) = M(n/2) + O(1) | Theta(log n) |
The Master Theorem Calculator gives "Θ(n log n)" for a = 2, b = 2, d = 1 and "Θ(log n)" for a = 1, b = 2, d = 0. To see where the work sits, the Recursion Tree Calculator lists each level: for a = 2, b = 2, d = 1 and n = 8 it shows 8 work on each of four levels, total 32.
Writing your own divide-and-conquer algorithm
- Find a way to split the input so that each part is a smaller instance of the same problem.
- Decide the base case: the size at which you answer directly.
- Work out the combine step and its cost. If combining is as hard as the original problem, the split has not helped.
- Write the recurrence and solve it before writing much code. If the answer is no better than the brute force, rethink the split.
- Test on sizes that are not powers of two, which is where off-by-one errors in the split hide.
When divide and conquer does not help
- The subproblems overlap. Divide and conquer assumes the parts are independent. Naive Fibonacci splits fib(n) into fib(n - 1) and fib(n - 2), but those share almost all of their own subproblems, so the same values are recomputed an exponential number of times. When subproblems repeat, store each answer once: that is dynamic programming.
- The combine step is too expensive. With T(n) = 2T(n/2) + Theta(n^2), the master theorem gives Theta(n^2): the root's work dominates, and splitting saved nothing over a direct quadratic method.
- There are too many subproblems. Splitting n by n matrices into blocks and making eight block products gives Theta(n^3), the same as the plain triple loop. Fewer recursive calls (seven, in Strassen's method) is what changes the exponent.
- The inputs are tiny. Recursion has overhead per call. Practical sorting code often switches to insertion sort once a piece is small, keeping the asymptotic bound while doing less work on small pieces.
Check yourself
- Why does computing x^(n // 2) twice, instead of once, make fast exponentiation linear? (M(n) = 2M(n/2) + O(1) is Case 1 of the master theorem with log_2 2 = 1 > 0, which gives Theta(n).)
- How many multiplications does the function above use for n = 1024? (11 squarings and 1 extra, 12 in all: 1024 is a 1 followed by ten 0s in binary.)