Bubble sort

The largest rises like a bubble · Part of Search and sort

Key idea

Practice

6 questions · about 3 min

Explained step by step

Bubble sort

Bubble sort walks the array left to right comparing each pair of neighbors: if the left one is larger, it swaps them. So in the 1st pass the largest element moves up 1 spot at a time to the end, like a bubble rising to the surface. In the 2nd pass, the second largest reaches the second-to-last spot. After n − 1 passes, everything is sorted.

To trace bubble sort by hand, you walk comparing neighbors and swapping when needed. With [4, 1, 3, 2]: 4 > 1, swap: [1, 4, 3, 2]; 4 > 3: [1, 3, 4, 2]; 4 > 2: [1, 3, 2, 4]. The 1st pass left 4 at the end. The 2nd puts 3 in place: [1, 2, 3, 4]. The 3rd swaps nothing.

Bubble sort can be improved with a flag: each pass records whether any swap happened. If a whole pass made no swap, the array is already sorted and it stops there. With that, if the array comes already sorted, 1 pass is enough: O(n). The worst case is still O(n²), but now it's adaptive.

In the worst case, bubble sort's passes look at n − 1, n − 2, ... down to 1 pairs: in total, (n − 1) × n / 2 comparisons, O(n²). It sorts in place, with just 2 indexes: O(1) memory. And each swap costs 3 operations, because a temporary variable is needed so no value is lost.

Bubble sort and insertion sort are both O(n²), stable, in place and adaptive. But insertion sort is faster in practice: to move an element, bubble swaps it over and over, 3 operations per step; insertion shifts the others with 1 assignment each and writes the element at the end. That's why bubble sort is taught a lot but barely used.

Stable sort

Bubble sort is stable: it only swaps 2 neighbors if the left one is strictly larger. If they're equal, it leaves them, so 2 equal elements never cross. That sets it apart from selection sort, which with its long-distance swap can scramble equal elements.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

The largest rises like a bubble