AQA GCSE Computer Science (8525), section 3.1.4 (Sorting algorithms)
How it works
A bubble sort puts a list in order by comparing pairs of neighbouring items and swapping them if they are in the wrong order. Going through the whole list once is called a pass. After each pass the largest unsorted item has "bubbled" to the end.
The sort stops when a whole pass is completed without any swaps, as that means the list is in order.
Steps (sorting into ascending order)
- Start at the first item.
- Compare it with the next item. If the first is bigger, swap them.
- Move along one place and repeat until the end of the list.
- If any swap was made in the pass, go back to the start for another pass.
- If no swaps were made, the list is sorted.
Worked example
Sort 5, 3, 8, 1, 4.
Pass 1
| Comparison | Action | List after |
|---|---|---|
| 5 and 3 | swap | 3, 5, 8, 1, 4 |
| 5 and 8 | no swap | 3, 5, 8, 1, 4 |
| 8 and 1 | swap | 3, 5, 1, 8, 4 |
| 8 and 4 | swap | 3, 5, 1, 4, 8 |
Pass 2: the list becomes 3, 1, 4, 5, 8.
Pass 3: the list becomes 1, 3, 4, 5, 8. Swaps were made, so another pass is needed.
Pass 4: no swaps are made, so the sort stops.
The sorted list is 1, 3, 4, 5, 8.
Pseudo-code
REPEAT
swapped ← False
FOR i ← 0 TO LEN(data) - 2
IF data[i] > data[i + 1] THEN
temp ← data[i]
data[i] ← data[i + 1]
data[i + 1] ← temp
swapped ← True
ENDIF
ENDFOR
UNTIL swapped = False
temp is needed so that one value is not lost when swapping.
Python
def bubble_sort(data):
swapped = True
while swapped:
swapped = False
for i in range(len(data) - 1):
if data[i] > data[i + 1]:
data[i], data[i + 1] = data[i + 1], data[i]
swapped = True
return data
print(bubble_sort([5, 3, 8, 1, 4])) # [1, 3, 4, 5, 8]
Advantages and disadvantages
| Advantages | Disadvantages |
|---|---|
| Simple to understand and write | Slow for large lists, as it makes many passes and comparisons |
| Needs no extra memory (it sorts in place) |
Common mistake: stopping after one pass, or after the list "looks" sorted. You are only sure it is sorted after a pass with no swaps. Also, when swapping two items, you need a temporary variable, or one value is lost.
Exam tip: show the list after each pass (or each swap, if asked). Say that the largest value is in its final place after the first pass.
Check yourself
What is a pass in a bubble sort?
One complete run through the list, comparing neighbouring pairs and swapping where needed.
How does the algorithm know when to stop?
When a complete pass is made without any swaps.
Perform one pass of a bubble sort on 4, 2, 7, 1.
2, 4, 1, 7.