Bubble sort puts data in order by comparing neighbours.
A bubble sort repeatedly compares neighbouring values.
If a pair is in the wrong order, the values are swapped.
β
Wrong order?
β
Swap
β
Move forward
Learn how bubble sort compares neighbouring values, swaps those in the wrong order and repeats passes until the list is sorted.
A bubble sort repeatedly compares neighbouring values.
If a pair is in the wrong order, the values are swapped.
During one pass, the algorithm moves from the start of the list to the end, comparing each neighbouring pair.
In ascending order, larger values gradually βbubbleβ towards the right.
Two neighbouring students compare heights. If the taller student is standing before the shorter student, they swap places.
The comparison then moves to the next pair. After several passes, the whole line is ordered.
The largest value is now in its final position.
The sort may stop after a maximum of number of items β 1 passes.
A more efficient version stops early when a complete pass makes no swaps.
For ascending order, swap when the left value is greater than the right value.
For descending order, swap when the left value is less than the right value.
| Skill | How it appears |
|---|---|
| Decomposition | The sort is divided into passes and comparisons. |
| Pattern recognition | The same compare-and-swap pattern repeats. |
| Abstraction | Only neighbouring values and their order matter. |
| Algorithmic thinking | The comparisons follow a precise sequence and stopping rule. |
FOR Pass β 1 TO LENGTH(Data) - 1
FOR Index β 0 TO LENGTH(Data) - 2
IF Data[Index] > Data[Index + 1]
THEN
Temp β Data[Index]
Data[Index] β Data[Index + 1]
Data[Index + 1] β Temp
ENDIF
NEXT Index
NEXT PassThe outer loop controls the passes. The inner loop compares neighbouring values. Temp safely stores one value while the swap takes place.
If the first value is overwritten immediately, it disappears before it can be moved.
Temp holds one value safely during the exchange.
Keep comparisons in order and clearly separate one pass from the next.
Compare neighbouring values only, and move exactly one position forward each time.
Bubble sort repeatedly compares neighbouring values and swaps those in the wrong order.
One complete journey through the data is called a pass. Passes continue until the maximum number is reached or a full pass makes no swaps.
A temporary variable is used when swapping values.
You have now explored the complete journey from analysing a problem to designing, tracing, searching and sorting algorithms.