COMPARISON SORTS
Bubble Sort, visualised
Bubble sort repeatedly compares two neighbouring elements and swaps them when they are out of order. After each pass, the largest remaining value has moved to the right end.
Run Bubble Sort in the visualizer →
Opens the Sorting Cinema visualizer with 12 elements in English.
How it works
- Starting from the left, compare each pair of neighbouring elements.
- If the left value is larger than the right value, swap them.
- After one pass, the largest value of the unsorted part is fixed at the right end.
- Repeat on the remaining range, excluding the fixed right end.
Complexity and stability
- Best
- O(n²)
- Average
- O(n²)
- Worst
- O(n²)
- Extra space
- O(1)
- Stability
- Stable
A common implementation stops early when a pass makes no swaps, giving a best case of O(n). This app's bubble sort does not stop early, so it still makes O(n²) comparisons on already sorted input.
Source of facts: Complexity follows the learning guide's comparison table and text, and this app's implementation.
Trace on a small array
The first operations on the input [5, 2, 4, 1, 3], following the same steps as the app.
| # | Operation | Array after |
|---|---|---|
| 1 | Swap [0]=5 and [1]=2 | [2, 5, 4, 1, 3] |
| 2 | Swap [1]=5 and [2]=4 | [2, 4, 5, 1, 3] |
| 3 | Swap [2]=5 and [3]=1 | [2, 4, 1, 5, 3] |
| 4 | Swap [3]=5 and [4]=3 | [2, 4, 1, 3, 5] |
| 5 | Compare [0]=2 and [1]=4 | [2, 4, 1, 3, 5] |
| 6 | Swap [1]=4 and [2]=1 | [2, 1, 4, 3, 5] |
| 7 | Swap [2]=4 and [3]=3 | [2, 1, 3, 4, 5] |
| 8 | Swap [0]=2 and [1]=1 | [1, 2, 3, 4, 5] |
…and so on. In this trace, 10 compare / swap / write operations in total produce [1, 2, 3, 4, 5].
Suitable inputs and caveats
- Good for watching the basics of comparing and swapping on a small input.
- In this app, even sorted input goes through every pass (no early exit).
- Comparisons grow roughly with the square of n, so it is not suited to large arrays.
FAQ
Why is bubble sort slow?
It only swaps neighbours, so a value that must travel far moves one position at a time, and the number of comparisons is O(n²).
Does it finish instantly on a sorted array?
An early-exit implementation finishes after one pass (O(n)), but this app's bubble sort has no early exit, so it still runs every pass of comparisons.
Is bubble sort stable?
Yes. It swaps only when the left value is strictly larger, so equal values keep their order.