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.