AlgoLab

O(n²)·O(1) space·stable
645559896316373459948511843281951114277

Starting bubble sort on an array of 20 items.

Starting bubble sort on an array of 20 items.
  1. 1for each pass through the array, from the first to the second-to-last
  2. 2compare each adjacent pair of values in the unsorted portion
  3. 3if the left value is greater than the right value, swap them
  4. 4if a full pass made no swaps, the array is already sorted
  5. 5the array is fully sorted
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(n)
AverageO(n²)
WorstO(n²)
Extra spaceO(1)
StableYes
n² at n=20 predicts 400; this run took 0.

Bubble sort

Bubble sort repeatedly scans the unsorted portion of the array, comparing each pair of adjacent values and swapping them if they are in the wrong order. Each full pass moves the largest remaining value into its correct position at the end of the array, so the array is sorted after at most n − 1 passes.

When it is the right choice

Bubble sort is genuinely not worth using in practice: insertion sort does the same job or better on every input while making far fewer writes, and any general-purpose language ships a library sort that outperforms both by a wide margin. Its only real value is pedagogical, as the simplest sorting algorithm to trace by hand. The early-exit optimisation below gives it a best case of O(n) on already-sorted input, but that is not a reason to reach for it.

How it works

Worth noticing

Cost

Best
O(n)
Average
O(n²)
Worst
O(n²)
Extra space
O(1)
Stable
Yes

Worth comparing

All algorithms