Intuition
Line people up by height and walk along the line, swapping any neighbours where the taller one stands first. By the end of the walk, the tallest person has been passed along to the far end. Walk again and the second tallest ends up next to them. Repeat until a walk makes no swaps.
How it works
- Compare
a[0]witha[1]; swap them if the first is larger. - Move one step right and repeat, up to the end of the unsorted part.
- The largest value is now last. Shrink the unsorted part by one.
- Start the next pass. If a whole pass made no swaps, the list is sorted: stop early.
Complexity
| Case | Comparisons | Swaps | When it happens |
|---|---|---|---|
| Best | n − 1 | 0 | Already sorted: one pass, then the early exit. |
| Worst | n(n − 1)/2 | n(n − 1)/2 | Reversed: every comparison swaps. |
Each swap fixes exactly one pair that was out of order, so the number of swaps always equals the number of such pairs in the input.
Common mistakes
- No early exit. Without the
swappedcheck, bubble sort does n(n − 1)/2 comparisons even on sorted input. - Running past the end. The inner loop compares
a[j]witha[j + 1], so it must stop one short of the unsorted part’s end. - Re-checking the sorted tail. Each pass can stop one position earlier than the last, because the end is already final.
When to use it
For teaching, and for tiny lists that are almost sorted. Insertion sort does the same job with fewer operations, and anything larger should use your language’s built-in sort.
Check yourself
Check yourself
After the first pass over [5, 1, 4, 2, 8], which value is certain to be in its final place?
Every pass carries the largest remaining value to the end. After the first pass the list is [1, 4, 2, 5, 8], with 8 in its final place.
Check yourself
How many swaps does bubble sort make on [1, 2, 3, 4, 5]?
Nothing is out of order, so no swaps. It makes 4 comparisons in the first pass, sees no swaps, and stops.
Sources
- Donald Knuth, The Art of Computer Programming, Vol. 3, section 5.2.2.
- Owen Astrachan, “Bubble Sort: An Archaeological Algorithmic Analysis,” SIGCSE 2003.
Finished this page?
Your list