compare
swap
sorted
5
0
3
1
8
2
1
3
9
4
2
5
Compare adjacent elements. If the left is bigger, swap them. Repeat until no swaps happen.
Think of bubbles — heavier ones rise. Bigger numbers bubble to the right end each pass.
start
1 / 94
SPD0.5×
click to pause · hover for controls · fullscreen for more

Bubble Sort

Repeatedly swapping adjacent elements

Visual by thisgirltech

BeginnerSorting

Bubble sort is named after the way it works: in each pass, the largest unsorted element "bubbles" all the way to its correct position on the right, like a bubble rising to the surface. After n−1 passes, every element has bubbled to its spot and the array is sorted.

Each pass compares every adjacent pair from left to right. Blue means the pair is being compared. Red means the pair is out of order and gets swapped. After each pass, one more green bar locks in permanently on the right — watch the green region grow leftward.

The animation also shows the early-exit optimisation: if a full pass completes without a single swap, the array must already be sorted and the algorithm stops immediately — no wasted work.

One bubble per pass

Every pass guarantees that the largest remaining unsorted element reaches its final position. Pass 1 places the maximum. Pass 2 places the second maximum. And so on.

Early exit optimisation

Track whether any swap happened in a pass. If the pass completed with zero swaps, the array is already sorted — stop immediately. Best case becomes O(n) on a nearly-sorted input.

Stable sort

Bubble sort only swaps elements that are strictly out of order — equal elements are never swapped past each other. Their original relative order is always preserved.

Most swaps of any O(n²) sort

On a reversed array, bubble sort makes n(n−1)/2 swaps — the theoretical maximum. Selection sort makes at most n−1 swaps on the same input. This is why bubble sort is almost never used in production.

TIP

Watch the Pass counter and Swaps counter together. Notice that early passes make many swaps while later passes make fewer — the array is getting progressively more sorted. If you see a pass with zero swaps, the early exit fires and the algorithm is done.

COLOUR LEGEND

Comparing
Swapping
Sorted
Unsorted