Step by step
The example above, written out — the same steps the animation plays.
- 1Start. 5 values. Bubble sort walks the list comparing neighbours, swapping any pair in the wrong order.
- 2Pass 1. Pass 1: the largest unsorted value will bubble to the end.
- 3Compare 5 and 3. 5 > 3 — out of order.
- 4Swap. Swap: 3 moves left, 5 moves right.
- 5Compare 5 and 8. 5 ≤ 8 — already in order.
- 6Compare 8 and 2. 8 > 2 — out of order.
- 7Swap. Swap: 2 moves left, 8 moves right.
- 8Compare 8 and 1. 8 > 1 — out of order.
- 9Swap. Swap: 1 moves left, 8 moves right.
- 108 is in place. End of pass 1: 8 has reached its final position.
- 11Pass 2. Pass 2: the largest unsorted value will bubble to the end.
- 12Compare 3 and 5. 3 ≤ 5 — already in order.
- 13Compare 5 and 2. 5 > 2 — out of order.
- 14Swap. Swap: 2 moves left, 5 moves right.
…and 14 more steps — press Play above to watch them all.
What's happening?
- Each pass walks the unsorted part from left to right, comparing pairs of neighbours.
- A pair in the wrong order swaps; after one pass the largest remaining value is at the end and never moves again.
- If a whole pass makes no swaps, the list is already sorted and the algorithm stops early.
Complexity
- Time
- O(n²) worst and average · O(n) best (already sorted)
- Space
- O(1) — it sorts in place
Where you'll meet it
Almost never used for real data — it exists to teach comparing, swapping and loop invariants. Libraries use merge sort, quicksort or Timsort instead.
Common mistake
Forgetting that each pass can stop one position earlier: after pass k, the last k values are already in place.
FAQ
Why is bubble sort O(n²)?
In the worst case each of about n passes compares about n pairs, so the work grows with n × n.
Is bubble sort stable?
Yes. Equal values are never swapped, so their original order is kept.
When does bubble sort finish in one pass?
When the list is already sorted: the first pass makes no swaps and the algorithm stops.