Skip to main content

Bubble Sort

Neighbor comparisons and swaps, with the sorted tail growing from the right each pass.

time O(n²)space O(1)Read the lesson
BeginnerO(n²)

Neighbor comparisons and swaps, with the sorted tail growing from the right each pass.

step 1 / 22

What's happening

Bubble sort repeatedly compares neighbors and swaps them when out of order. Largest values "bubble" to the end. Array size: 6.

comparisons: 0swaps: 0writes: 0
comparingswappingkey heldwritingpivotfinal position

Watch the sorted tail grow from the right each pass, and how a clean pass triggers the early exit. Try a nearly-sorted input like “1, 2, 4, 3, 5, 6”. Markers: ▲ compared · ⇄ swap.

Understand the algorithm

time O(n²)space O(1)

What it is

Bubble sort repeatedly walks the array comparing neighbors and swapping out-of-order pairs, so the largest remaining value 'bubbles' to the end of each pass.

Why it matters

It is usually the first sort people meet, and its value is pedagogical: neighbor comparisons, a growing sorted tail, and an early-exit optimization are all visible in one tiny algorithm. It also gives a visceral feel for why O(n²) hurts.

How it works

  1. 1Compare each adjacent pair left to right; swap when the left one is larger.
  2. 2After one pass, the largest unsorted value sits at the end, locked.
  3. 3Repeat on the shrinking unsorted prefix.
  4. 4A full pass with no swaps means the array is sorted, exit early.

Real-world uses

  • Teaching sorting and loop invariants
  • Detecting 'almost sorted' input cheaply (one clean pass exits)
  • Rarely used in production, and knowing why is the point

Strengths

  • Trivial to implement and reason about
  • Stable, equal elements keep their order
  • O(n) best case on already-sorted input with the early exit

Limitations

  • O(n²) comparisons and swaps on average, hopeless at scale
  • More writes than insertion sort (swaps vs shifts)
  • Outclassed by insertion sort even among the simple sorts

Watch the early exit on nearly-sorted input.