Merge Sort: Split the Pile, Then Merge Two Sorted Piles
Ms Kate's eight exam papers sorted in 24 steps: split in half until each pile is one paper, then merge sorted piles by taking the lower top. A million papers take about 20 million steps, and the price is extra room.
What you will learn
- Explain merging two sorted piles by always taking the lower top paper
- Trace merge sort splitting down to single papers and merging back up
- Say why merge sort costs O(n log n) whatever the input order
- Explain the price of merge sort: a second place to work in
Before you start
- Recursion
- Insertion Sort
Ms Kate has marked eight exam papers, and they're in the order she marked them: 38, 27, 43, 3, 9, 82, 10, 55. She wants them in order of score. The same problem shows up for the whole school, with a million papers, and sorting a pile like that one paper at a time takes a lot of steps. Here, eight papers will be sorted in just twenty-four steps.
Two sorted piles
Imagine two piles of exam papers. Jack sorted one and Emma sorted the other, lowest score on top. Look at just the two top papers, 3 and 9. Take the lower one, 3, and put it on a new pile. Again: the tops are 27 and 9, so take 9. Then 27 and 10, take 10. You only ever look at two papers, and each paper is moved only once.
But where do sorted piles come from? Split the big pile in half, and again, and again, until each pile is just one paper. One paper on its own is always sorted. So: split until each pile is one paper, then merge the sorted piles back up. That's merge sort.
Split down, merge up
Split the pile in the middle: two piles of four. Split again: four piles of two. And again: eight piles of one, each sorted. Now merge: 38 and 27 become 27, 38. 43 and 3 become 3, 43. Those two become 3, 27, 38, 43. The right side goes the same way to 9, 10, 55, 82. The last merge turns two sorted piles of four into one.
The last merge, slowly
Two sorted piles, 3, 27, 38, 43 and 9, 10, 55, 82. Watch the top of each:
- 3 is lower than 9: take 3 from the left.
- 9 is lower than 27: take 9 from the right. Then 10.
- 27, 38 and 43 are each lower than 55: take them from the left.
- The left pile is empty, so take 55, then 82, from the right.
One sorted pile in eight steps, one step for every paper placed.
The code
import merger
show = True
def sort(papers):
n = len(papers)
if n == 1:
return papers # one paper is sorted
mid = n // 2
left = sort(papers[:mid])
right = sort(papers[mid:])
pile = merger.merge(left, right)
if show:
print(f"{left} + {right} = {pile}")
return pile
One paper is already sorted, so hand it back. Otherwise split in the middle and sort each half. sort calls itself, once for the left half and once for the right. Then merge the two sorted halves.
steps = 0
def merge(left, right):
global steps
pile = [0] * (len(left) + len(right))
i, j = 0, 0
for k in range(len(pile)):
steps += 1
if (j == len(right)
or (i < len(left) and left[i] <= right[j])):
pile[k] = left[i] # take from the left pile
i += 1
else:
pile[k] = right[j] # take from the right pile
j += 1
return pile
A new pile with room for both, and i and j point at the top paper of each. One loop for every place in the new pile, one step each. If the right pile is empty, or the left top is lower or equal, take from the left; otherwise take from the right. Only the two top papers are ever compared.
import merge_sort
import merger
scores = [38, 27, 43, 3, 9, 82, 10, 55]
merge_sort.sort(scores)
print("Steps: " + str(merger.steps))
[38] + [27] = [27, 38]
[43] + [3] = [3, 43]
[27, 38] + [3, 43] = [3, 27, 38, 43]
[9] + [82] = [9, 82]
[10] + [55] = [10, 55]
[9, 82] + [10, 55] = [9, 10, 55, 82]
[3, 27, 38, 43] + [9, 10, 55, 82] = [3, 9, 10, 27, 38, 43, 55, 82]
Steps: 24
A million papers
import random
import merge_sort
import merger
merge_sort.show = False
for n in (1_000, 10_000, 100_000, 1_000_000):
scores = [random.randint(0, 100) for _ in range(n)]
merger.steps = 0
merge_sort.sort(scores)
nn = n * n
print(f"{n:9,d} papers: {merger.steps:,d} steps (n x n {nn:,d})")
1,000 papers: 9,976 steps (n x n 1,000,000)
10,000 papers: 133,616 steps (n x n 100,000,000)
100,000 papers: 1,668,928 steps (n x n 10,000,000,000)
1,000,000 papers: 19,951,424 steps (n x n 1,000,000,000,000)
Halving a million takes only twenty levels, and every level places a million papers: about twenty million steps. Putting every paper against every other paper would be up to about a million million. The scores are random, but the step count depends only on how many papers there are, because every merge places each paper exactly once.
Where it breaks: room
Merge sort doesn't care about the order of the papers. A messy pile, a pile in order or a pile backwards all take the same steps. A pile already in order is still split and merged the same way. The catch is room.
Take two sorted piles side by side in one row: 5, 8 and 6, 7. Merge them in the same row, with no new pile. 5 is lower than 6, so it goes in the first spot, where it already sits. Fine. Now 6 is lower than 8, so the 6 must go in the second spot. But the 8 is sitting there and isn't placed yet. The 6 goes in and the 8 is wiped out, and you can never get it back.
So a merge needs a second place to work in: a new row as big as both piles together. Then nothing is wiped out, and you fill the new row 5, 6, 7, 8. That's why merge builds a new pile. The price is extra room, one spot for every paper.
The cost
| Part | Cost |
|---|---|
| Halving into levels | log n levels (3 for 8 papers, 20 for a million) |
| Merging one level | n steps, every paper placed once |
| Whole sort, any input order | O(n log n) |
| Extra room | O(n), a second place as big as the piles |
Compare insertion sort, which is O(n²) on shuffled input, and quick sort, which works in place but depends on its pivot.
Where you meet merge sort
- The sort button in a language: Java and Python sort their lists with a method built on merging.
- A database sorting a huge table sorts small parts, then merges them, even when the table doesn't fit in memory.
- A search joining many servers: each sends back a sorted list, and merging them gives one sorted list.
- Sorting by name, then by city: merge sort keeps equal items in their old order, so the first sort isn't undone.
Try it yourself
Add two more scores to make ten papers, and predict the merge lines before you run it.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
Big-O: Reading Cost From Code, With Handshakes and a Guest Book
Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.
Recursion: Russian Dolls, the Base Case and the Call Stack
Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.
Linear vs Binary Search: Page by Page, or Open in the Middle
Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.
Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.
