Divide, solve, combine
Every divide-and-conquer algorithm has the same three steps:
- Divide the input into smaller instances of the same problem.
- Solve each instance recursively; instances small enough are solved directly (the base case).
- Combine the partial answers into the answer for the whole input.
You have already met two. Merge sort divides trivially (cut the array in the middle), solves both halves, and does its real work when it combines: merging two sorted halves in linear time. Quicksort is the mirror image: all the work is in the divide step (partitioning around a pivot), and combining costs nothing because the halves are already in place.
The pattern pays off when the pieces are genuinely smaller, independent of each other, and cheap to combine. If the pieces overlap, as in the naive recursive Fibonacci, the same subproblem is solved again and again; that is the signal for dynamic programming instead.
Recurrences
The running time of a recursive algorithm is naturally described in terms of itself. If merge sort takes T(n) time on n elements, then
T(n) = 2·T(n/2) + c·n (two halves, plus a linear merge)
T(1) = c
This is a recurrence. Reading it is mechanical: the number in front of T is how many recursive calls each call makes (a), the argument is how big each subproblem is (n/b), and the extra term is the work done outside the recursive calls, in dividing and combining (f(n)).
| Algorithm | Recurrence | Solution |
|---|---|---|
| Binary search | T(n) = T(n/2) + c | Θ(log n) |
| Merge sort | T(n) = 2T(n/2) + cn | Θ(n log n) |
| Quickselect, perfect pivot every time | T(n) = T(n/2) + cn | Θ(n) |
| Quicksort or quickselect, worst pivot every time | T(n) = T(n − 1) + cn | Θ(n²) |
| Karatsuba multiplication | T(n) = 3T(n/2) + cn | Θ(n^log₂3) ≈ Θ(n^1.585) |
Floors and ceilings (n/2 when n is odd) almost never change the asymptotic answer, and the usual convention is to drop them.
The recursion tree
The most reliable way to solve a recurrence is to draw what it does. For merge sort:
level 0: n cost n
level 1: n/2 n/2 cost n
level 2: n/4 n/4 n/4 n/4 cost n
...
level log₂n: 1 1 1 ... 1 (n leaves) cost n
Each level does n work in total (2^i subproblems of size n/2^i) and there are log₂ n + 1 levels, so T(n) = Θ(n log n). The general recipe:
- Work out the cost of the nodes on level i: there are a^i of them, each of size n/b^i, each costing f(n/b^i).
- Count the levels: about log_b n until the size reaches 1.
- Add up the levels. Usually one of three things happens: the levels cost about the same (multiply by the number of levels), the costs grow geometrically towards the leaves (the leaves dominate), or they shrink geometrically (the root dominates).
For a perfectly split quickselect, T(n) = T(n/2) + cn: one node per level, costing n, n/2, n/4, … That geometric series sums to less than 2n, so the root dominates and T(n) = Θ(n). The difference from quicksort is only the number of recursive calls, a = 1 instead of 2, and it changes n log n into n.
The Master theorem
The three outcomes of the recursion tree are exactly the three cases of the Master theorem. It applies to recurrences of the form
T(n) = a·T(n/b) + f(n) with constants a ≥ 1 and b > 1, and f(n) asymptotically positive
Compare f(n) with n^(log_b a), the total cost of the leaves (there are a^(log_b n) = n^(log_b a) of them):
- Leaves dominate. If f(n) = O(n^(log_b a − ε)) for some constant ε > 0, then T(n) = Θ(n^(log_b a)).
- Balanced. If f(n) = Θ(n^(log_b a)), then T(n) = Θ(n^(log_b a) · log n). (A common extension: if f(n) = Θ(n^(log_b a) · log^k n) with k ≥ 0, then T(n) = Θ(n^(log_b a) · log^(k+1) n).)
- Root dominates. If f(n) = Ω(n^(log_b a + ε)) for some constant ε > 0, and the regularity condition a·f(n/b) ≤ c·f(n) holds for some constant c < 1 and all large n, then T(n) = Θ(f(n)).
The regularity condition says the work really does shrink from one level to the next. It holds for every ordinary polynomial f, but it is part of the theorem and must be checked.
Applying it:
- Merge sort: a = 2, b = 2, n^(log₂2) = n, f(n) = n. Case 2: Θ(n log n).
- Binary search: a = 1, b = 2, n^(log₂1) = n⁰ = 1, f(n) = 1. Case 2: Θ(log n).
- Perfect quickselect: a = 1, b = 2, n^0 = 1, f(n) = n = Ω(n^(0 + 1)). Regularity: 1 · (n/2) ≤ ½ · n, so c = ½ works. Case 3: Θ(n).
- Karatsuba: a = 3, b = 2, n^(log₂3) ≈ n^1.585, f(n) = n = O(n^(1.585 − 0.5)). Case 1.
- Strassen's matrix multiplication: a = 7, b = 2, f(n) = n². log₂7 ≈ 2.807 > 2. Case 1: Θ(n^2.807).
When the Master theorem does not apply
The theorem is a shortcut for one specific shape. Outside that shape it says nothing, and forcing it gives wrong answers.
- Subtract instead of divide. T(n) = T(n − 1) + n (quicksort's or quickselect's worst case, insertion sort written recursively) has no b > 1. The recursion tree is a path of n nodes costing n, n − 1, …, 1: Θ(n²). Likewise T(n) = 2T(n − 1) + 1 is Θ(2^n).
- Unequal splits. T(n) = T(n/3) + T(2n/3) + n has two different subproblem sizes. The recursion tree still works: every full level costs n, and the longest path has log_{3/2} n levels, so T(n) = Θ(n log n). (The Akra–Bazzi method generalises the Master theorem to such sums.)
- A gap between the cases. T(n) = 2T(n/2) + n / log n: f(n) is smaller than n, but not by a polynomial factor n^ε, so case 1 does not apply, and it is not Θ(n log^k n) with k ≥ 0 either. The recursion tree gives Θ(n log log n).
- A non-constant number of subproblems. T(n) = √n · T(√n) + n: a is not a constant.
- Random splits. Quickselect with a random pivot does not split at a fixed fraction: the subproblem size is a random variable. Its expected cost needs a probabilistic argument (below), not the theorem.
- Median of medians: T(n) ≤ T(n/5) + T(7n/10) + cn, again two different sizes. Because 1/5 + 7/10 < 1, each level of the recursion tree costs at most 9/10 of the level above, so the total is a geometric series: Θ(n).
Selection: the k-th smallest value
The selection problem: given n values and an index k, return the value that would be at position k if the values were sorted. This lesson uses 0-based k: k = 0 is the minimum, k = n − 1 the maximum, and k = ⌊(n − 1)/2⌋ a median. The lab writes it as "k = 3 (4th smallest)" to keep the two conventions apart.
Sorting solves it in O(n log n). The minimum and maximum need only one pass, O(n). Quickselect gets any k in expected O(n), by noticing that quicksort does too much work: after a partition, the pivot is at its final index p, and only one side can contain index k.
quickselect(items, k):
low, high = 0, n − 1
loop:
if low == high: return items[low] # one slot left: it is index k
p = partition(items, low, high) # pivot lands at its final index p
if k == p: return items[p]
if k < p: high = p − 1 # keep the left side only
else: low = p + 1 # keep the right side only
Because there is only one recursive call, it is a loop: no recursion, O(1) extra space. k stays an absolute index, so it never needs adjusting when the range narrows.
This implementation
The partition is exactly the quicksort lesson's: Lomuto, the middle element low + (high − low)/2
swapped to the end as pivot, strict <, invariant items[low..i) < pivot ≤ items[i..j). At the end
the pivot swaps into slot i. Every pivot placed this way holds the value sorting would put there, which
the lab shows in green. Slots outside the live range are faded: they are never looked at again.
In the Median of nine preset (k = 4), watch the brackets in front of the array: one per round, each narrower than the last. The array is reordered as a side effect; afterwards everything left of k is ≤ the answer and everything right of it is ≥. That partial order is often what callers want (for example, "the 10 smallest, in any order").
Cost: expected linear, worst case quadratic
One round over a range of size m costs m − 1 comparisons. The total depends entirely on how fast the range shrinks.
Best and typical case. If each pivot lands near the middle, the sizes are n, n/2, n/4, …, and the total is under 2n comparisons. The Sorted input preset is the extreme: the middle element of sorted input is its median, so k = 7 of 15 is found in one round of 14 comparisons.
Expected case with a random pivot. Call a pivot good if it lands in the middle half of the range; then the kept side has at most 3/4 of the elements. A random pivot is good with probability ½, so on average it takes 2 rounds to shrink the range by a factor 3/4. The expected total is at most 2(n + 3n/4 + 9n/16 + …) = 8n, which is O(n). A finer analysis (Knuth) gives about 3.4n comparisons for the median.
Worst case. If every pivot is the smallest or largest value in the range, each round removes one element: (n − 1) + (n − 2) + … + 1 = n(n − 1)/2 comparisons, Θ(n²). The middle pivot does not prevent this. It makes sorted and reversed input easy, but for any rule that takes the pivot from a fixed position (or a few fixed positions), an adversary can build an input that hits a bad pivot every round. For the middle rule, such inputs are easy to generate by running the algorithm backwards.
There is also a much more ordinary trigger: many equal keys. In the All equal preset no value is strictly less than the pivot, so every pivot lands at the left end of its range. With k = n − 1 each round discards one slot: 45 comparisons for 10 values, n(n − 1)/2. (With k = 0 the first pivot lands on k and it finishes in one round: the worst case depends on k as well as the data.) The fix is the same as for quicksort: a three-way partition (less, equal, greater), which stops as soon as k falls into the equal block.
| Version | Expected time | Worst case | Extra space |
|---|---|---|---|
| Sort, then index | O(n log n) | O(n log n) | depends on the sort |
| Quickselect, fixed pivot rule (this lesson) | O(n) on typical inputs | O(n²) | O(1) |
| Quickselect, random pivot | O(n) for every input | O(n²), with tiny probability | O(1) |
| Median of medians (BFPRT, 1973) | O(n) | O(n) | O(log n) recursion stack |
| Introselect (quickselect with a fallback) | O(n) | O(n) or O(n log n), depending on the fallback | O(1) |
| Heap of size k | O(n log k) | O(n log k) | O(k) |
"Expected O(n) for every input" with a random pivot is an average over the algorithm's coin flips, not over inputs: no input is bad on purpose, though an unlucky run still can be.
Median of medians, briefly
To guarantee linear time, choose the pivot carefully: split the range into groups of 5, take the median of each group, and recursively select the median of those medians. At least about 3/10 of the elements are then smaller than the pivot and about 3/10 larger, so the kept side has at most about 7n/10 elements. That gives the recurrence T(n) ≤ T(n/5) + T(7n/10) + cn = Θ(n) shown above. The constant factor is large, so in practice it is used as a fallback: introselect runs ordinary quickselect and switches to a guaranteed method only when the range is not shrinking fast enough.
The teaching implementation
Quickselect.Select / quickselect takes the array, k and a comparison; it throws on k outside
0…n − 1, then runs the loop above. The listings are the exact files the tests run. Every language reads
one shared fixture (the value, the exact comparison count and the exact array order left behind,
including all-equal input, duplicates, negatives and k at both ends) and checks 500 random arrays
against sorting, including that the result is partitioned around k.
Language notes
| Language | Built-in selection | Notes |
|---|---|---|
| C# | None documented. | Sort a copy (Array.Sort) and index it, or keep the k smallest in a PriorityQueue<T, T> (a min-heap: enqueue with a negated priority, or use a reversed comparer, to keep a max-heap of size k). LINQ's Order().ElementAt(k) returns the right value; how much of the sort it performs is an implementation detail. |
| Python | None that is linear. | heapq.nsmallest(k + 1, data)[-1] is O(n log k). statistics.median_low returns a median; it currently works by sorting, so treat it as O(n log n). sorted(data)[k] is simplest. |
| Java | None. | Arrays.sort on a copy, then index; or a PriorityQueue with Comparator.reverseOrder() holding the k + 1 smallest. |
| C++ | std::nth_element(first, nth, last) |
Rearranges so that *nth is the element sorting would put there, with nothing greater before it and nothing smaller after it: the same contract as this implementation. The standard requires linear time on average; implementations typically use introselect. std::partial_sort gives the k smallest in sorted order. |
Common mistakes
- Mixing 0-based and 1-based k. "The 3rd smallest" is k = 2. Decide once and document it.
- Recursing into both sides. That is quicksort again: O(n log n), and you lose the point.
- Adjusting k when going right in an implementation that keeps absolute indices. Only a version
that copies the subarray (so indices restart at 0) needs
k −= p + 1. - Assuming the middle pivot makes the worst case impossible. It makes common inputs fast; it does not defend against crafted input or many equal keys.
- Forgetting that the input is reordered. Copy first if the caller's order matters.
- Applying the Master theorem to T(n) = T(n − 1) + n or to unequal splits. Draw the tree instead.
Edge cases
- n = 1: the loop returns immediately; no partition happens (zero comparisons).
- k = 0 or k = n − 1: still correct; for these, a single scan for the minimum or maximum (n − 1 comparisons) is simpler and never worse.
- Duplicates: the answer is a value, and which copy ends up at k is not specified. The lab tags copies (5a, 5b) so you can follow them.
- k outside 0…n − 1 and empty arrays are rejected, not answered with a guess.
Worked practice
1. Solve T(n) = 4T(n/2) + n² with the Master theorem.
Answer
a = 4, b = 2, n^(log₂4) = n². f(n) = n² = Θ(n²): case 2, so T(n) = Θ(n² log n). In the recursion tree every level costs n² (4^i nodes of size n/2^i, each (n/2^i)²) and there are log₂ n levels.
2. Does the Master theorem solve T(n) = 2T(n/2) + n log n? If so, how?
Answer
Not with the basic three cases: n log n is larger than n = n^(log₂2) but not by a polynomial factor n^ε, so case 3 does not apply. The extended case 2 does, with k = 1: T(n) = Θ(n log² n).
3. In the All equal preset, why does k = 9 cost 45 comparisons but k = 0 only 9?
Answer
With strict <, no element is less than the pivot, so i never moves and the pivot always lands at the
left end of the range. For k = 0 that is exactly k after the first round (9 comparisons). For k = 9
each round discards just the pivot slot and keeps the other m − 1: 9 + 8 + … + 1 = 45.
4. Quickselect does at most n − 1 comparisons in its first round. Why is the total still O(n) on average rather than O(n log n)?
Answer
Only one side is kept, so the round sizes form a (roughly) geometric series n, cn, c²n, … with c < 1 on average, which sums to O(n). Quicksort processes both sides, so every level of its recursion tree costs about n, and there are about log n levels.
5. You need the 100 largest of 10 million scores, in sorted order. What would you use?
Answer
Either a min-heap of size 100 (O(n log 100), one pass, works on a stream), or quickselect for
k = n − 100 followed by sorting the 100 elements at or above it (expected O(n + 100 log 100)). In C++,
std::nth_element then std::sort on the tail, or std::partial_sort.
Summary
- Divide and conquer: divide into smaller copies, solve them, combine; the cost is a recurrence.
- A recursion tree solves almost any recurrence: cost per level, number of levels, then sum.
- Master theorem for T(n) = aT(n/b) + f(n): compare f(n) with n^(log_b a); case 3 also needs regularity. It does not cover T(n − 1) recursions, unequal or random splits, or gaps such as n/log n.
- Quickselect partitions like quicksort but keeps only the side holding index k: expected O(n), worst case O(n²), O(1) extra space.
- The middle pivot is good on sorted input but not a guarantee; equal keys with Lomuto are quadratic.
Median of medians gives O(n) worst case; introselect (as in typical
std::nth_elementimplementations) uses it as a fallback.