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.
Watch a Bubble Sort
Sorting into ascending order (smallest to largest, or A to Z).
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
Compare & Swap
Are the highlighted items in the right order (ascending), or do they need to swap?
Pass by Pass
Type the list as it will be at the end of the pass, separated by commas.
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.
Run the Code
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.
Write & Mark
Complete the Explanation
Choose the right word for each gap.