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.
Split down, then merge up
Quick check: the stages
Have a go
Quick check: the stages
3 questionsMerging takes the smaller front item
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.
Make a free account to save your work and track your progress.
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.
Watch: merge sort, split and merge
Press Play on the short film below. It sorts the list 5, 3, 8, 1 with merge sort. Watch which two items are compared at each step of a merge.
Film: merge sort
Merge sort
Every scene, as text
- Merge sort splits the lesson's list [5, 3, 8, 1] in half: half of 4 items is 2, so [5, 3] and [8, 1]. It splits each part again until every part has one item, [5], [3], [8] and [1], and a part with one item is already sorted.
- Then it merges the parts in pairs, the two items compared ringed: 5 with 3, taking the smaller, 3, first, to give [3, 5]; and 8 with 1, to give [1, 8]. Each new part is sorted.
- Myth (false): to merge, join the two parts and sort them again. Joined, [3, 5] + [1, 8] is [3, 5, 1, 8], which is not sorted, so it would need a whole new sort, throwing away the order each part already has.
- The cure, the lesson's worked example: both parts are sorted, so compare only their fronts (ringed) and take the smaller. Fronts 3 and 1: take 1. Fronts 3 and 8: take 3. Fronts 5 and 8: take 5. The left part is now empty, [], so the rest, 8, goes on the end: [1, 3, 5, 8] in 3 comparisons.
- Split down, then merge up: the whole of merge sort on [5, 3, 8, 1], the shape of the lesson's picture. Each small merge took 1 comparison and the last took 3, so 5 in all for these 4 items with this lesson's merge. Merge sort is fast on big lists, but each merge makes a new list, so it needs extra memory.
Extra: A function that calls itself
In code, merge sort is often written with recursion. Recursion means a function calls itself on a smaller problem. The function merge_sort calls merge_sort on each half.
It needs a base case (a problem small enough to answer at once). Here it is a list of 0 or 1 items. That list is already sorted, so the function gives it back and stops. Without a base case it would never stop.
Extra: Try it: the whole merge sort
def merge(left, right):
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))
return result + left + right
def merge_sort(items):
print("Sorting", items)
if len(items) <= 1:
return items
middle = len(items) // 2
left = merge_sort(items[:middle])
right = merge_sort(items[middle:])
return merge(left, right)
print(merge_sort([5, 3, 8, 1]))
# items[:middle] is the first half. items[middle:] is the rest.
# Read the printed lines. They follow the picture at the top.
Make a free account to save your work and track your progress.
Benefits and drawbacks of merge sort
| Benefits | Drawbacks |
|---|---|
| Fast on big lists | Needs extra memory for the new lists it makes |
| Takes about the same work whether the list is messy or nearly sorted | The code is harder to write and to understand |
| The work is easy to share between computers | For a very short list, a simple sort can be quicker |
The cells students fill in are left blank in this preview.
Match the word to its meaning
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Quick check: which sort?
Have a go
Quick check: which sort?
4 questionsYour turn: build the merge
Build the parts of merge sort.
middle_point(items)gives back where to split a list: half the number of items, using//. So 5 items split at 2.merge(left, right)joins two sorted lists into one sorted list. Take the smaller front item each time. When one list runs out, add what is left of the other.is_sorted(items)gives back True if a list is in order, and False if not.
Press Run Tests to check.
def middle_point(items):
# Give back the index where a list is split in two.
# It is half the number of items. For 5 items it is 2. For 4 items it is 2.
return None
def merge(left, right):
# left and right are both sorted. Give back one new sorted list with all the items.
# Look at the front item of each list. Take the smaller one. Repeat.
# When one list runs out, add the rest of the other list.
return None
def is_sorted(items):
# Give back True if every item is smaller than or equal to the next one.
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Key words crossword
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Exit quiz
Have a go