About this visualization
Bubble sort repeatedly compares neighbouring items and swaps them if they are in the wrong order, so the largest values bubble to the end of the list. It is slow on large inputs but perfect for learning how sorting works. Type your own numbers and watch every comparison and swap with live counters.
How it works
- Compare items i and i+1; swap if the left one is larger.
- After pass k, the last k items are in their final place.
- Stop early if a whole pass makes no swap — the list is sorted.
Worked example
Sort [5, 1, 4, 2]. Pass 1 compares (5,1) swap, (5,4) swap, (5,2) swap → [1, 4, 2, 5]. Pass 2 compares (1,4) fine, (4,2) swap → [1, 2, 4, 5]. Pass 3 finds nothing to swap, so it stops: 6 comparisons and 4 swaps in total.
Enter these numbers in the simulator above to see every step.
Complexity and properties
| Best case | |
|---|---|
| Average case | |
| Worst case | |
| Space | |
| Stable | Yes |
| In-place | Yes |
Best case relies on the early-exit check.
When to use it
- Learning the idea of swapping adjacent elements before moving to faster sorts.
- Counting comparisons and swaps for homework.
- Seeing the best case when the list is already sorted.
Frequently asked questions
What is the time complexity of bubble sort?
in the average and worst case, and in the best case when the input is already sorted and the early-exit check is used. Space complexity is .
Is bubble sort stable?
Yes. It only swaps adjacent items that are strictly out of order, so equal items keep their relative order.
Why is bubble sort rarely used in practice?
It makes many more comparisons and swaps than merge sort, quick sort or heap sort on large inputs.