Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.11 (3 of 4): Merge sort

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

50 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it means
Merge sortSplit the list in two again and again. Then merge the sorted parts back together.
DivideSplit a big problem into smaller ones.
MergeJoin two sorted lists into one sorted list.
Sub-listA smaller list that is a part of a bigger list.
HalfOne of two equal parts of a list.
FrontThe first item of a sorted part.
FunctionA named piece of code that gives back a result.
SortedIn order, smallest first.
MemoryThe space a program needs to hold its data.

The cells students fill in are left blank in this preview.

Split down, then merge up

A tree from 5 3 8 1, split into 5 3 and 8 1, then into 5, 3, 8 and 1, which merge into 3 5 and 1 8 and then into 1 3 5 8.A tree from 5 3 8 1, split into 5 3 and 8 1, then into 5, 3, 8 and 1, which merge into 3 5 and 1 8 and then into 1 3 5 8.

Quick check: the stages

Have a go

Quick check: the stages

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Merging 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

StepFront of leftFront of rightTakeResult so far
1311 (the smaller)1
23831, 3
35851, 3, 5
4none left88 (the rest)1, 3, 5, 8

The cells students fill in are left blank in this preview.

Try it: merge two sorted lists

Code: python
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

RoundWhat happensParts after the round
Split 1Split 5 3 8 1 in two5 3 and 8 1
Split 2Split each part again5 and 3 and 8 and 1
Merge 1Merge 5 with 3. Merge 8 with 13 5 and 1 8
Merge 2Merge 3 5 with 1 81 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

Code: python
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

BenefitsDrawbacks
Fast on big listsNeeds extra memory for the new lists it makes
Takes about the same work whether the list is messy or nearly sortedThe code is harder to write and to understand
The work is easy to share between computersFor 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your turn: build the merge

Build the parts of merge sort.

  1. middle_point(items) gives back where to split a list: half the number of items, using //. So 5 items split at 2.
  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.
  3. is_sorted(items) gives back True if a list is in order, and False if not.

Press Run Tests to check.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.