Divide and conquer: split, solve, merge
Comparing every pair of a million numbers takes about 500 billion comparisons, yet merge sort sorts them in about 20 million steps. It splits the list until each piece is trivial, then merges the pieces back in one pass per level. That shape, and how to count its cost, is divide and conquer.
01 Too big to solve? Make it smaller
Some problems are easy when they are small. A list of one number is already sorted. Divide and conquer uses that: break the problem into smaller copies of itself, solve those the same way, and build the answer from theirs.
- Divide: split the input into parts, usually two halves.
- Conquer: solve each part with a recursive call. A part that is small enough is the base case, answered directly.
- Combine: turn the parts’ answers into the answer for the whole.
Merge sort is the cleanest example, because each move is simple. Dividing is cutting the list in the middle. Combining is merging two sorted lists into one.
02 Merge sort in full
merge_sort never compares two items itself. It only splits and hands the halves on. The comparing is all in merge, which relies on one promise: both lists it is given are already sorted.
03 Going down: halve until one item is left
Follow [5, 2, 7, 1, 6, 3, 8, 4] down. Each call cuts its piece in two and passes both halves on, until every piece holds one item.
- one piece
- the next piece
Splitting moves nothing: the order is unchanged. It only decides which items belong together. At level 3 every piece has one item, so every piece is sorted.
Eight items take 3 levels of halving, because 8 → 4 → 2 → 1 is three halvings. In general the number of levels is how many times you can halve n before reaching 1: about log₂ n.
04 The merge: one pass over both halves
Merging is where the work is. Both lists are sorted, so the smallest item left is always at the front of one of them. Compare the two fronts, take the smaller, and move that side on. You never look back.
- compared next
- just placed
- already placed
- not filled yet
- waiting / placed earlier
Both halves are sorted already; that is what the recursive calls returned. i and j start at the front of each, and out is empty.
Every step places one item, so merging two halves with n items between them takes n steps and at most n − 1 comparisons. That is O(n), and it is only possible because both halves arrived sorted.
05 Coming back up: merge level by level
As the calls return, each level merges pairs of neighbouring pieces. Single items become sorted pairs, pairs become sorted fours, and the last merge gives the whole sorted list.
- one piece
- the next piece
Every level touches each of the 8 items exactly once. All the sorting happens here, in the merges.
06 Count the work: n per level, log n levels
Add up the merging one level at a time. Each level merges pieces that together hold all n items, so each level costs about n steps, however many pieces there are. There are about log₂ n levels. So the total is about n × log₂ n.
| n | Levels (log₂ n) | Moves (n × levels) | Every pair compared (n² / 2) |
|---|---|---|---|
| 8 | 3 | 24 | 32 |
| 1,024 | 10 | 10,240 | 524,288 |
| 1,048,576 | 20 | 20,971,520 | about 550 billion |
Written as a recurrence, the cost of sorting n items is two sorts of n/2 plus a merge of n: T(n) = 2T(n/2) + n. The table is that recurrence unrolled: log₂ n levels of n each.
07 Other splits, other costs
The same three questions give the cost of any divide and conquer: how many parts do you solve, how big are they, and what do the split and the combine cost?
| Algorithm | Parts solved | Split + combine cost | Total |
|---|---|---|---|
| Binary search | 1 of 2 halves | O(1), no combine | O(log n) |
| Merge sort | 2 halves | O(n) merge | O(n log n) |
| Quicksort | 2 parts around a pivot | O(n) partition, no combine | O(n log n) on average, O(n²) worst |
| Merge k sorted lists in pairs | k/2 merges per round | all N nodes per round | O(N log k) |
Quicksort moves the work to the split: it partitions around a pivot first, so there is nothing left to do once both sides are sorted. Merging k lists is merge sort’s combine step on its own: merge them in pairs, halving the number of lists each round, so there are log₂ k rounds and each touches all N nodes.
08 When it goes wrong
if len(a) == 0:
return aA base case one step too lowFor one item, mid is 0, so the halves are [] and the same one-item list. The call repeats itself forever and ends in RecursionError. Stop at len(a) <= 1.pivot = a[0] # on sorted inputUneven splitsThe log n levels come from halving. A quicksort that always splits off one item has n levels, so it does O(n²) work and recurses n deep. Balance is what makes the count work.if left[i] < right[j]:Using < in the mergeStill sorted, but equal items from the right half now go first, so the sort is no longer stable: records that tie keep no fixed order. <= keeps the left one first.merge_sort(a[:mid])Slices are copiesEach slice copies its items, so this version uses O(n) extra memory and allocates a lot. It is fine for learning. Library versions merge through one reused buffer and typically switch to insertion sort for very small pieces.Splitting alone does not make anything faster. If you solve both halves and the combine still compares every item with every other, you are back at O(n²). The gain comes from a combine step that is linear, or from solving only one part.