Mathematics ยท WDM11 (D1)
Bubble sort
An algorithm is a finite set of precise instructions. Bubble sort puts a list in order by comparing neighbours.
One pass
Compare the 1st and 2nd items; swap if they are in the wrong order. Then compare the 2nd and 3rd, and so on to the end. After the first pass the largest item (for ascending order) is at the end.
When to stop
Repeat passes, each one comparison shorter than the last. Stop when a pass makes no swaps: the list is sorted.
Counting
For a list of n items, the first pass makes n - 1 comparisons. In the worst case bubble sort needs n - 1 passes.
Worked example
Carry out the first pass of an ascending bubble sort on 5, 1, 4, 2.
- 5 > 1: swap gives 1, 5, 4, 2
- 5 > 4: swap gives 1, 4, 5, 2
- 5 > 2: swap gives 1, 4, 2, 5
Answer: After pass 1: 1, 4, 2, 5
Check yourself
- How many comparisons does the first pass of a bubble sort make on a list of 8 items?
Show answer
7. n - 1 = 7.
- After the first pass of an ascending bubble sort, where is the largest item?
- At the start
- At the end of the list
- In the middle
- It has not moved
Show answer
At the end of the list. The largest item is carried to the end in the first pass.
- What is 3, 1, 2 after one pass of an ascending bubble sort?
- 1, 3, 2
- 3, 2, 1
- 2, 1, 3
- 1, 2, 3
Show answer
1, 2, 3. 3 > 1: swap to 1, 3, 2; 3 > 2: swap to 1, 2, 3.
- When does a bubble sort stop?
- When a full pass makes no swaps
- After exactly two passes
- When the first item is smallest
- After n comparisons
Show answer
When a full pass makes no swaps. No swaps in a pass means every neighbouring pair is in order.
- In the worst case, how many passes does bubble sort need for 6 items?
Show answer
5. n - 1 = 5 passes.
Sources
Last updated 7 November 2026. Spotted a mistake? Email alevel@lifereadysociety.com.