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. Larger values "bubble up" to the end of the list after each pass.
n ← length_of_list
swapped ← TRUE
WHILE swapped = TRUE DO
swapped ← FALSE
FOR i ← 1 TO n - 1
IF list[i] > list[i + 1] THEN
temp ← list[i]
list[i] ← list[i + 1]
list[i + 1] ← temp
swapped ← TRUE
ENDIF
NEXT i
n ← n - 1
ENDWHILE
temp variable is essential for swapping — you must store one value temporarily while overwriting it. Without temp, data would be lost. Also note: n ← n - 1 is an optimisation — after each pass, the last item is already sorted, so you can ignore it.5>3 → swap | 5<8 → no swap | 8>1 → swap | 8>4 → swap
35148✓ 8 is now in position
3<5 → no | 5>1 → swap | 5>4 → swap
314583>1 → swap | 3<4 → no
13458| Property | Detail |
|---|---|
| Maximum passes (n items) | n − 1 passes in the worst case |
| Comparisons per pass | Decreases by 1 each pass (optimised version) |
| Early termination | Stops if a pass completes with no swaps (already sorted) |
| Stability | Stable — equal elements keep their original relative order |
| In-place | Yes — only needs one extra variable (temp) for swapping |
temp variable when swapping — writing list[i] ← list[i+1] directly destroys the original value5 questions · 12 marks
| Term | Definition |
|---|
10 minutes · mixed marks