Bubble sort (enrichment)
Enrichment: repeatedly swap adjacent out-of-order pairs.
Syllabus says: “Not in the PCCST303 syllabus — supplementary”
On this page · 9 sections
Compare NEIGHBOURS, swap if out of order; the biggest bubbles to the end each pass. No swaps in a pass → already sorted, stop.
Soda bubbles rising: the biggest bubble reaches the top first.
Bubble sort repeatedly compares adjacent elements and swaps them if they are in the wrong order; after pass i the i largest elements are in their final places. (Enrichment — not in the PCCST303 syllabus.)
Why this is here
Bubble sort is NOT part of the PCCST303 syllabus. It is included as supplementary material because many students meet it first.
Definition
Each pass compares a[j] and a[j+1] for every j and swaps them if out of order, so the largest remaining value “bubbles” to the end. With an early-exit flag, a pass with no swaps ends the sort.
Worked example
| Input | 5 1 4 2 8 |
|---|---|
| After pass 1 | 1 4 2 5 8 |
| After pass 2 | 1 2 4 5 8 |
| After pass 3 | 1 2 4 5 8 |
Totals: comparisons = 9, swaps = 4
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
Algorithm
- Step 1:Start.
- Step 2:Read the number of elements n.
- Step 3:Read the n elements into the array A.
- Step 4:Repeat for i = 0 to n-2:
- Repeat for j = 0 to n-i-2: if A[j] > A[j+1], swap A[j] and A[j+1] (temp = A[j], A[j] = A[j+1], A[j+1] = temp).
- Step 5:Display the sorted array A.
- Step 6:Stop.
This is the plain lab-record version. Adding a flag that stops when a pass makes no swap gives the O(n) best case.
Pseudocode used by the animated lab · the lines highlighted in the visualizer
- 1BubbleSort(a, n)
- 2for pass ← 0 to n − 2
- 3for j ← 0 to n − 2 − pass: if a[j] > a[j+1]
- 4swap a[j], a[j+1]; swapped ← true
- 5if not swapped: stop
- 6end
Complexity
Best O(n) with the early-exit flag (already sorted), average and worst O(n²). Stable, in-place.
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
References
- Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — Ch. 2, 6, 7, 8, 11 Problem 2-2
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)