Bubble sort is a simple sorting algorithm that works by repeatedly comparing adjacent pairs of elements and swapping them if they are in the wrong order. After each pass through the list, the largest unsorted element "bubbles up" to its correct position at the end.
Sort [5, 3, 8, 1, 2] using bubble sort:
| Pass | List state | Swaps made |
|---|---|---|
| Pass 1 | [3, 5, 1, 2, 8] | 3: (5,3), (5,8 no), (8,1), (8,2) → 8 in place |
| Pass 2 | [3, 1, 2, 5, 8] | 2: (3,5 no), (5,1), (5,2) → 5 in place |
| Pass 3 | [1, 2, 3, 5, 8] | 2: (3,1), (3,2) → 3 in place |
| Pass 4 | [1, 2, 3, 5, 8] | 0 swaps → STOP (list sorted) |
Best case: The list is already sorted. One pass with 0 swaps is needed → n-1 comparisons total.
Worst case: The list is in reverse order. n passes each comparing n elements → roughly n² comparisons total.
Bubble sort is considered inefficient for large lists because its worst-case performance is quadratic. For small lists, it is easy to understand and implement.
Bubble sort can be optimised by keeping track of whether any swap occurred in a pass. If no swaps happened, the list is already sorted and the algorithm can stop early. This is the optimised/early exit bubble sort.
8 Edexcel-style questions · instantly marked
| Term | Definition |
|---|
Timed exam-style test. No hints until submission.