- Home
- Lessons
- KS3 Computing
- Sorting: bubble sort
Sorting: bubble sort
๐ฌ The doodle video for this lesson is coming soon. Subscribe on YouTube to see it first.
Sorting puts data in order, such as scores from lowest to highest. Bubble sort is the simplest sorting algorithm to follow by hand.
How bubble sort works
1. Compare the first two items. If they are in the wrong order, swap them.
2. Move along one place and compare the next pair. Keep going to the end of the list. That is one pass.
3. After each pass, the biggest unsorted item has 'bubbled' to the end.
4. Repeat passes until a whole pass makes no swaps. Then the list is sorted.
2. Move along one place and compare the next pair. Keep going to the end of the list. That is one pass.
3. After each pass, the biggest unsorted item has 'bubbled' to the end.
4. Repeat passes until a whole pass makes no swaps. Then the list is sorted.
One pass on 5, 3, 8, 1, 4
5 and 3: swap. 5 and 8: no swap. 8 and 1: swap. 8 and 4: swap.
After pass 1: 3, 5, 1, 4, 8. The 8 is now in its final place.
After pass 2: 3, 1, 4, 5, 8.
After pass 1: 3, 5, 1, 4, 8. The 8 is now in its final place.
After pass 2: 3, 1, 4, 5, 8.
Good and bad points
Bubble sort is easy to understand and code, and sorts the list in place without extra memory.
But it is slow on big lists, because it makes many comparisons and can need many passes.
For large lists, faster algorithms such as merge sort are used.
But it is slow on big lists, because it makes many comparisons and can need many passes.
For large lists, faster algorithms such as merge sort are used.
Show the list 6, 2, 9, 4 after the first pass of bubble sort.
- 6 and 2: swap: 2, 6, 9, 4.
- 6 and 9: no swap.
- 9 and 4: swap: 2, 6, 4, 9.
Answer: 2, 6, 4, 9
Bubble sort compares neighbouring pairs and swaps them if they are in the wrong order. Each pass moves the largest unsorted item to the end. It stops after a pass with no swaps. Simple, but slow for big lists.
Check you have got it
Answer 6 quick questions with instant marking. If you get one wrong, GCSE-ready shows you why and gives you another go. It is free, and you do not need an account.