sort.cny.shStart a race
Back to library
01 / 18Algorithm

Bubble Sort

Repeatedly swap neighbors that are out of order.

StableIn-place
BestO(n)
AverageO(n²)
WorstO(n²)
01How it works

Walk the array pairwise and swap any two neighbors that are in the wrong order. Each full pass bubbles the largest remaining element to the end; after n−1 passes the array is sorted. An early-exit flag lets an already-ordered input finish in a single pass.

02Best for

Teaching the idea of comparisons and swaps — it's the simplest sort that actually works. Also fine on tiny arrays or data that's already nearly sorted, where the early-exit flag kicks in immediately.

03Avoid when

Anything production-sized. Quadratic time with constant-memory shuffling makes it strictly worse than insertion sort for the same niche, and dramatically worse than any O(n log n) option past a few dozen elements.