How It Works · Passes & Swaps · Pseudocode · Trace Table
CSZoneCambridge IGCSE Computer Science 0478
How Bubble Sort Works
Comparing Adjacent Items
Bubble sort: repeatedly steps through the list comparing adjacent pairs. If a pair is in the wrong order, they are swapped. The largest values "bubble up" to the end with each pass.
Start: 5 3 8 1 4
Pass 1: 3 5 1 4 8 ← 8 bubbles to end
Pass 2: 3 1 4 5 8
Pass 3: 1 3 4 5 8 ← sorted!
Bubble Sort Pseudocode
Cambridge 0478 Pseudocode
n ← LENGTH(data) FOR i ← 1 TO n - 1 FOR j ← 1 TO n - i IF data[j] > data[j+1] THEN temp ← data[j] data[j] ← data[j+1] data[j+1] ← temp ENDIF NEXT j NEXT i
The swap uses a temp variable to hold one value while the other is moved — without temp, a value would be lost
Number of Passes & Efficiency
Performance of Bubble Sort
For a list of n items: maximum n-1 passes. After each pass, the largest remaining unsorted item is in its correct position — so comparisons reduce each pass.
Optimisation: if no swaps occur in a full pass, the list is already sorted — the algorithm can stop early using a swapped flag variable.
Bubble sort is not efficient for large lists — but simple to understand and code. Cambridge 0478 expects you to trace it and write it in pseudocode.
Exam Practice
Have a go at this question
Cambridge IGCSE 0478 style
The list [4, 2, 7, 1] is sorted using bubble sort. Show the state of the list after each pass, and state how many swaps occurred in total.