Bubble sort orders an array by repeatedly comparing adjacent pairs and swapping them if they're in the wrong order.
The intuition. After ONE pass through the array, the largest element 'bubbles' to the end. After two passes, the largest TWO are at the end. After n-1 passes, the array is sorted.
Cambridge pseudocode:
FOR Pass ← 1 TO N-1
FOR Counter ← 1 TO N-Pass
IF Array[Counter] > Array[Counter+1] THEN
Temp ← Array[Counter]
Array[Counter] ← Array[Counter+1]
Array[Counter+1] ← Temp
ENDIF
NEXT Counter
NEXT Pass
Why three lines for the swap. Without the temporary variable, the second assignment would overwrite the first value before it gets used.
Trace example. Sorting [5, 3, 8, 1, 6]:
- Pass 1: [3, 5, 8, 1, 6] → [3, 5, 8, 1, 6] → [3, 5, 1, 8, 6] → [3, 5, 1, 6, 8]. Largest at end.
- Pass 2: [3, 5, 1, 6, 8] → [3, 1, 5, 6, 8] → [3, 1, 5, 6, 8]. Second-largest in place.
- Pass 3: [1, 3, 5, 6, 8] → [1, 3, 5, 6, 8]. Sorted.
- Pass 4: no swaps. Done.
Strengths. Simple to code. Works on any comparable data type.
Weaknesses. Worst-case O(n²) — slow on large arrays. Real-world systems use quicksort, mergesort or built-in language sorts instead. Bubble sort is a TEACHING algorithm.
Optimisation. If a pass makes NO SWAPS, the array is already sorted — exit early.
Cambridge tip. Mark scheme rewards the SWAP using a TEMP variable explicitly. Three lines: temp ← A; A ← B; B ← temp.