OCR J277 · 2.1.3 Searching and Sorting Algorithms

Bubble Sort

Mr Brown

What Is a Bubble Sort?

A bubble sort puts a list in order. It compares each item with the item next to it and swaps them if they are in the wrong order. Larger items gradually “bubble” towards the end of the list. One run through the list is called a pass, and the passes are repeated until a whole pass needs no swaps.

Interactive Demo

Watch a Bubble Sort

Sorting into ascending order (smallest to largest, or A to Z).

Being comparedJust swappedIn its final place
Pass 0
Comparisons 0
Swaps 0

The steps

  • Start at the first item in the list
  • Compare it with the next item. If they are in the wrong order, swap them
  • Move on one place and repeat until you reach the end of the list — that is one pass
  • After each pass, the largest item still being sorted is in its final place at the end
  • Repeat passes until a pass makes no swaps — the list is sorted

Pre-requisites

  • The data must be in a list (an array) whose items can be compared and put in order — numbers, or text in alphabetical order
  • The list does not need to be sorted already — that is the whole point!

Try It

Interactive Practice

Compare & Swap

Are the highlighted items in the right order (ascending), or do they need to swap?

Pass 1
Right first time 0 / 0
Interactive Practice

Pass by Pass

Type the list as it will be at the end of the pass, separated by commas.

Passes right 0 / 0

The Algorithm

In the exam, a bubble sort may be shown as code or in OCR Exam Reference Language. You don't need to remember it, but you must recognise it and explain what each part does. Click a line to see what it does, or step through it.

Interactive Demo

Run the Code

n
swapped
i
temp
list

How to spot a bubble sort

  • An inner loop compares each item with the next one (list[i] and list[i + 1])
  • A swap using a temporary variable (temp)
  • An outer loop that repeats the passes, usually controlled by a swapped flag

Sample Questions

Write your answer, then reveal the mark scheme and tick each point you included.

Interactive Practice

Write & Mark

Interactive Practice

Complete the Explanation

Choose the right word for each gap.

Bubble Sort Challenges

Complete

0

Points

0
Challenge

Loading challenge…