SLIDE 1
CSZone.co.uk
Click to advance · Arrow keys also work
Cambridge IGCSE 0478 · Topic 7 · 7.3a

Bubble Sort
Algorithm

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.
4 marks
Start: 4 2 7 1
Pass 1: 2 4 1 7 (3 swaps) [1]
Pass 2: 2 1 4 7 (1 swap) [1]
Pass 3: 1 2 4 7 (1 swap) [1]
Total swaps: 5 [1]
Key Takeaways

What to Remember

Bubble sort: compare adjacent pairs; swap if out of order; largest values bubble to the end
Swap requires a temp variable: temp←a, a←b, b←temp — never skip this step
Max n-1 passes for n items; can optimise with a "no swaps" flag to stop early
Not efficient for large lists — but simple enough to trace and write in an exam