Watch bubble sort swap neighbours on eight tiles, one pass at a time, with the code beside it. Type your own numbers to see the O(n) best and O(n²) worst case.
About this algorithm
Bubble sort walks along the list comparing each pair of neighbours and swapping any pair in the wrong order. It takes O(n²) time on average and in the worst case, and O(n) on a list that is already sorted, because a pass with no swaps stops it early. The largest value is carried all the way to the end on the first pass, like a bubble rising, then the next largest on the second pass, and so on.
Bubble sort is a teaching sort: it shows comparing and swapping neighbours with nothing else in the way, and the early exit shows why checking for a quiet pass matters. Real code rarely uses it. Insertion sort makes exactly the same number of swaps with fewer comparisons and is just as simple, so it is the better pick for small or nearly sorted data. Selection sort keeps writes to a minimum. For anything large use merge sort, quick sort or heap sort, which run in n log n time.
Start a pass at the first pair. If the left value is bigger than the right one, swap them. Then move one slot right and compare the next pair.
Whatever is the largest value in the unsorted part gets swapped forward at every comparison it meets, so by the end of the pass it sits in its final slot. That slot is left out of every later pass.
Keep a swapped flag, cleared at the start of each pass and set by any swap.
If a whole pass finishes without one swap, every neighbour pair is in order, so the list is sorted. Without this check the loop would always run n - 1 passes.
The page opens on the tiles 5 2 1 8 3 4 7 6. Pass 1: 5 swaps past 2 and past 1, then meets the bigger 8 and stays. Now 8 is carried right, swapping past 3, 4, 7 and 6. The row is 2 1 5 3 4 7 6 8, after 7 comparisons and 6 swaps, and 8 is done. Pass 2: 2 swaps past 1, 5 swaps past 3 and 4, and 7 swaps past 6, giving 1 2 3 4 5 6 7 8 after 6 comparisons and 4 swaps. Pass 3 compares the five pairs left and swaps nothing, so the sort stops after 3 of the 7 passes it could have run. The totals are 18 comparisons and 10 swaps, and 10 is exactly the number of pairs that started out of order.
A big value near the front moves to the end in one pass, but a small value near the end moves left only one slot per pass. The list 2 3 4 5 1 needs four passes for the 1 to reach the front. Cocktail shaker sort fixes this by sweeping in both directions.
Time: every swap fixes one out-of-order pair and a list can have up to n(n - 1)/2 of them, while an already sorted list ends after one quiet pass of n - 1 comparisons. Space: it swaps in place and keeps only the pass counter and the swapped flag.