Two teachers, two piles of papers
Two teachers must put 200 exam papers in order by name. Each teacher takes 100 and sorts them.
Now they have two sorted piles. They put them side by side. They look at the top paper of each pile and take the one that comes first. They do this again and again, until one sorted pile is left.
A computer does the same, but it splits much further: until each pile has one item. This method has a name: merge sort means split, then merge.
Key words
| Word | What it means |
|---|---|
| Merge sort | Split the list in two again and again. Then merge the sorted parts back together. |
| Divide | Split a big problem into smaller ones. |
| Merge | Join two sorted lists into one sorted list. |
| Sub-list | A smaller list that is a part of a bigger list. |
| Half | One of two equal parts of a list. |
| Front | The first item of a sorted part. |
| Function | A named piece of code that gives back a result. |
| Sorted | In order, smallest first. |
| Memory | The space a program needs to hold its data. |
The cells students fill in are left blank in this preview.
Quick check: the stages
Have a go
Quick check: the stages
3 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
The clever part: merging
To merge two sorted lists, look at the front item of each. Take the smaller one. Do it again with the new fronts.
You never need to look further back. This is quick, because both lists are already in order.
Worked example: merging 3, 5 and 1, 8
| Step | Front of left | Front of right | Take | Result so far |
|---|---|---|---|---|
| 1 | 3 | 1 | 1 (the smaller) | 1 |
| 2 | 3 | 8 | 3 | 1, 3 |
| 3 | 5 | 8 | 5 | 1, 3, 5 |
| 4 | none left | 8 | 8 (the rest) | 1, 3, 5, 8 |
The cells students fill in are left blank in this preview.
Try it: merge two sorted lists
left = [3, 5]
right = [1, 8]
result = []
while len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
print("Result so far:", result)
result = result + left + right
print("Merged:", result)
# pop(0) takes the front item out of a list.
# Change the two lists. Keep each one sorted.
Many small merges
Merge sort splits a list until every part has one item. A part with one item is already sorted.
Then it merges. First it merges parts of 1 into parts of 2. Then parts of 2 into parts of 4. Each round uses the same merge you just did. Look at the picture again to follow it.
Worked example: merge sort, round by round
| Round | What happens | Parts after the round |
|---|---|---|
| Split 1 | Split 5 3 8 1 in two | 5 3 and 8 1 |
| Split 2 | Split each part again | 5 and 3 and 8 and 1 |
| Merge 1 | Merge 5 with 3. Merge 8 with 1 | 3 5 and 1 8 |
| Merge 2 | Merge 3 5 with 1 8 | 1 3 5 8 |
The cells students fill in are left blank in this preview.