Data Structures

Bubble Sort

Compare neighboring values and swap them if out of order. Large values bubble rightward until they settle at the end.

A bar-chart simulator of bubble sort

Press Play or advance one step at a time. Drag the slider to seek. Nearly sorted demonstrates early termination.

Best caseO(n)
AverageO(n²)
Worst caseO(n²)
Extra spaceO(1)
StableYes
Maximum comparisonsn(n−1)/2

Each pass fixes one maximum value

During a pass, the larger value in each comparison moves right, leaving the interval's maximum at the end. The next pass excludes that final position. If a whole pass makes no swaps, the array is sorted and the algorithm stops. This gives O(n) time on already sorted input.

Coding exercises: swaps equal inversions

An inversion is a pair i < j with a[i] > a[j]. Each bubble-sort swap removes exactly one inversion, so the swap count equals the inversion count. For large n, count inversions using Merge Sort in O(n log n), rather than simulating every swap.