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 (2 of 4): Bubble sort and insertion 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

Sort your hand of cards

You hold five playing cards. You want them in order, from the smallest to the largest. How do you do it?

Some people swap cards that are in the wrong order, again and again. Others take one card at a time and slide it into the right place. These are two real sorting methods. Computers use them too.

Key words

WordWhat it meansExample
Sorting algorithmA set of steps that puts items in order.
Bubble sortCompare neighbours and swap them if they are in the wrong order. Repeat in passes.
Insertion sortTake one item at a time and slide it into its place in the sorted part.
PassOne trip through the list from start to end.not the Python word pass
SwapTwo items change places.
ComparisonChecking one value against another.
In orderSmallest first. This is called ascending order.

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

Bubble sort: swap the neighbours

In a bubble sort you go along the list. Compare each item with the one next to it. If they are in the wrong order, swap them.

The biggest item "bubbles" to the end in the first pass. Do more passes. Stop when a whole pass makes no swaps.

Try it: bubble sort

Code: python
numbers = [5, 3, 8, 1]
swapped = True
pass_number = 0

while swapped:
    swapped = False
    pass_number = pass_number + 1
    for i in range(len(numbers) - 1):
        if numbers[i] > numbers[i + 1]:
            temp = numbers[i]
            numbers[i] = numbers[i + 1]
            numbers[i + 1] = temp
            swapped = True
    print("After pass", pass_number, numbers)

# Try [1, 2, 3, 4]. How many passes now?

Make a free account to save your work and track your progress.

Worked example: bubble sort

PassList at the startWhat happensList at the end
15, 3, 8, 15 and 3 swap. 5 and 8 stay. 8 and 1 swap3, 5, 1, 8
23, 5, 1, 83 and 5 stay. 5 and 1 swap. 5 and 8 stay3, 1, 5, 8
33, 1, 5, 83 and 1 swap. The rest stay1, 3, 5, 8
41, 3, 5, 8No swaps at all. The list is sorted: stop1, 3, 5, 8

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

Match the pass to the list

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Insertion sort: slide into place

In an insertion sort the left part of the list is always sorted. At the start it is just the first item.

Pick the next item. Slide it left, past every bigger item, until it fits. Now the sorted part is one item longer. Repeat until the end.

Worked example: insertion sort

StepItem pickedWhat happensList after the step
StartThe sorted part is just the 55, 3, 8, 1
135 is bigger, so it moves right. 3 goes in front3, 5, 8, 1
285 is smaller, so 8 stays where it is3, 5, 8, 1
318, 5 and 3 are all bigger and move right. 1 goes at the front1, 3, 5, 8

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

Try it: insertion sort

Code: python
numbers = [5, 3, 8, 1]

for i in range(1, len(numbers)):
    current = numbers[i]
    position = i - 1
    while position >= 0 and numbers[position] > current:
        numbers[position + 1] = numbers[position]
        position = position - 1
    numbers[position + 1] = current
    print("After picking", current, numbers)

# Try [9, 7, 5, 3, 1].

Make a free account to save your work and track your progress.

Quick check: how they work

Have a go

Quick check: how they work

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

Watch: two ways to sort

Press Play on the short film below. It sorts the list 5, 3, 8, 1 twice, once with each sort. Watch which items are compared, and count the passes bubble sort needs before it stops.

Film: bubble sort and insertion sort

Bubble sort and insertion sort

Every scene, as text

  1. Bubble sort, pass 1, on the lesson's list [5, 3, 8, 1]: each item is compared with its neighbour (the two ringed), and the two swap if the first is bigger. 5 and 3 swap, 5 and 8 stay, 8 and 1 swap, so after the pass the list is [3, 5, 1, 8]: in this first pass the biggest item, 8, bubbles to the end.
  2. Myth (false): one pass is enough to sort the list. After the first pass the list is [3, 5, 1, 8]: 5 is still in front of 1, so it is not sorted yet.
  3. The cure: keep going until a whole pass makes no swaps. The second pass swaps 5 and 1, giving [3, 1, 5, 8]; the third swaps 3 and 1, giving [1, 3, 5, 8]. The list is sorted, but bubble sort only knows it when the fourth pass makes no swaps and it stops: 4 passes, 12 comparisons and 4 swaps, because this version checks every pair in every pass.
  4. Insertion sort, like sorting cards in your hand: the left part of the list (underlined) is always sorted, at the start just the 5, and ▼ marks the item picked. Pick 3: 5 moves right and 3 goes in front, [3, 5, 8, 1]. Pick 8: 5 is smaller, so 8 stays. Pick 1: 8, 5 and 3 all move right and 1 goes in front, [1, 3, 5, 8].
  5. Two methods, one answer: both give [1, 3, 5, 8]. Bubble sort made 12 comparisons and 4 swaps, because this version checks every pair in every pass; insertion sort made 5 comparisons and 4 moves, an item moving one place right, and it is quick when a list is nearly sorted. Bubble sort is slow on big lists.

Benefits and drawbacks

BenefitsDrawbacks
Bubble sortVery simple to write. Stops early if the list is already sorted. Needs almost no extra memorySlow on big lists. Makes many swaps
Insertion sortSimple. Quick when the list is nearly sorted. Good for small lists or for items that arrive one at a time. Needs almost no extra memorySlow on big lists that are in a very wrong order

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

Your turn: two sorts

Write four functions. Do not change the list you are given: start with an empty list called result and use append to copy each item into it.

  1. one_bubble_pass(items) does one pass of bubble sort and gives back the new list.
  2. bubble_sort(items) gives back a new sorted list.
  3. insertion_sort(items) does the same with insertion sort.
  4. bubble_passes(items) counts the passes bubble sort makes. The last pass, with no swaps, counts too. So [5, 3, 8, 1] needs 4 passes, and a list already in order needs 1.

Press Run Tests to check.

Code: python
def one_bubble_pass(items):
    # Do ONE pass of bubble sort on a copy of the list and give the copy back.
    # Go from the start. Compare each item with the next one. If the first is bigger, swap them.
    # [5, 3, 8, 1] becomes [3, 5, 1, 8]. Do not change the original list.
    return items


def bubble_sort(items):
    # Give back a new sorted list, smallest first. Use bubble sort.
    # Do not change the original list.
    return items


def insertion_sort(items):
    # Give back a new sorted list, smallest first. Use insertion sort.
    # Do not change the original list.
    return items


def bubble_passes(items):
    # How many passes does bubble sort make? Count every pass,
    # including the last pass that has no swaps and tells it to stop.
    # [5, 3, 8, 1] needs 4 passes. [1, 2, 3] needs 1 pass.
    return 0

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.