Bubble Sort

Watch bubble sort push the biggest bar to the right, one neighbor swap at a time. Comparison/swap counters and synced pseudocode show exactly why O(n²) is slow.

Algorithm

Array

Size48
ComparingSwap/writePivot/keyReadSorted
Speed50×

Comparisons

0

Swaps/writes

0

Step

0/1,722

Reads

0

Aux memory

0

Call depth

1/1

Slow the speed and use Step to match the pseudocode highlight with the bar colors.

Pseudocode

for i ← 0 to n−1

for j ← 0 to n−i−2

if a[j] > a[j+1]

swap a[j] ↔ a[j+1]

// a[n−1−i] 확정

Time complexity

BestO(n)
AverageO(n²)
WorstO(n²)
SpaceO(1)
StableYes

Bubble sort repeatedly compares adjacent elements and swaps them when the left one is larger. After each pass the largest remaining value 'bubbles up' to the end, which is where the name comes from.

It needs about n²/2 comparisons, giving an average of O(n²) — but an early-exit flag makes it O(n) on already-sorted input. It is a stable sort: equal values never get reordered. Sorting Visualizer

Frequently asked questions

Is bubble sort ever useful?
Rarely in production — but it is O(n) on nearly-sorted input with early exit, and it is the clearest way to see why nested loops are slow.
Is bubble sort stable?
Yes — equal values are never swapped, so their original order is preserved.

Other algorithms