Skip to content

Divide and conquer: split, solve, merge

Working knowledgeConcept

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.py
def merge_sort(a):
if len(a) <= 1:
return a # one item is already sorted
mid = len(a) // 2
left = merge_sort(a[:mid]) # split, and solve each half
right = merge_sort(a[mid:])
return merge(left, right) # merge the two answers
def merge(left, right):
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])

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.

Going down: each level halves every piece. Colours mark the pieces.
Level 0 · 1 piece of 8
5
2
7
1
6
3
8
4
Level 1 · 2 pieces of 4
5
2
7
1
6
3
8
4
Level 2 · 4 pieces of 2
5
2
7
1
6
3
8
4
Level 3 · 8 pieces of 1
5
2
7
1
6
3
8
4
  • 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.

merge([1, 2, 5, 7], [3, 4, 6, 8]): one item placed per step
Step 1 of 9
Items placed 0
left · sorted half
i10
21
52
73
right · sorted half
j30
41
62
83
out · the merged piece
next0
1
2
3
4
5
6
7
  • 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.

0 comparisons

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.

Coming back up: each level merges neighbouring pieces into one sorted piece
Level 3 · 8 sorted pieces of 1
5
2
7
1
6
3
8
4
Level 2 · merged into 4 sorted pairs
2
5
1
7
3
6
4
8
Level 1 · merged into 2 sorted fours
1
2
5
7
3
4
6
8
Level 0 · merged into 1 sorted eight
1
2
3
4
5
6
7
8
  • 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.

Item moves in merge sort, counted by running the code above on shuffled input
nLevels (log₂ n)Moves (n × levels)Every pair compared (n² / 2)
832432
1,0241010,240524,288
1,048,5762020,971,520about 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.

Compare every pair (e.g. insertion sort)O(n²)Double the input and the work goes up four times.
Merge sortO(n log n)Double the input and the work goes up a little over twice: one extra level.

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?

Divide and conquer algorithms side by side
AlgorithmParts solvedSplit + combine costTotal
Binary search1 of 2 halvesO(1), no combineO(log n)
Merge sort2 halvesO(n) mergeO(n log n)
Quicksort2 parts around a pivotO(n) partition, no combineO(n log n) on average, O(n²) worst
Merge k sorted lists in pairsk/2 merges per roundall N nodes per roundO(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.

09 Check yourself

Question

Merge sort runs on 1,024 items. How many levels of merging are there, and about how many item moves in total?

Question

Binary search also halves the input. Why is it O(log n) and not O(n log n)?

Question

You merge two sorted lists of 5 items each. What is the most comparisons the merge can need?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?