How Bubble Sort Works — A Visual Step-by-Step Guide

5 min read

// key takeaways

  • Bubble Sort repeatedly compares adjacent elements and swaps them when they are out of order, so after each pass the largest remaining value is locked into its final position at the end of the array.
  • Bubble Sort runs in O(n²) time on average because it makes n(n−1)/2 comparisons and can only move an element one position per swap.
  • With an early-exit swapped flag, Bubble Sort finishes already-sorted input in a single pass, giving it an O(n) best case.
  • Bubble Sort is stable and sorts in place with O(1) extra space, but in practice it is only suited to teaching, tiny inputs, and checking whether an array is already sorted.

Bubble Sort is usually the first sorting algorithm anyone learns, and for good reason: you can hold the entire idea in your head at once. It repeatedly walks through the array, compares each pair of neighbours, and swaps them when they are out of order. Large values "bubble up" to the end of the array, one pass at a time.

In this guide we will walk through exactly what happens on every pass, watch the algorithm run step by step, and be honest about where Bubble Sort belongs in practice (spoiler: almost nowhere — but the *reasons* teach you more than most algorithms do).

The fastest way to understand Bubble Sort is to watch it run. The interactive visualizer animates every comparison and swap with the pseudocode line highlighted as it executes.

Open the Bubble Sort visualizer

The core idea in one sentence

Compare adjacent elements and swap them if the left one is bigger; after each full pass, the largest remaining value is guaranteed to be in its final position at the end of the array.

That guarantee is the key insight. After pass 1, the biggest element is at the last index — it cannot go any further right. After pass 2, the second-biggest is in place, and so on. The sorted region grows from the right end of the array, so each pass can stop one element earlier than the last.

Step-by-step walkthrough

Take the array [5, 2, 8, 1, 4]. Here is the first pass, comparison by comparison:

  1. Compare 5 and 2 → 5 > 2, swap[2, 5, 8, 1, 4]
  2. Compare 5 and 8 → already in order, no swap → [2, 5, 8, 1, 4]
  3. Compare 8 and 1 → 8 > 1, swap[2, 5, 1, 8, 4]
  4. Compare 8 and 4 → 8 > 4, swap[2, 5, 1, 4, 8]

Notice what happened: 8 — the largest value — was picked up mid-pass and carried all the way to the end. That is the "bubble". Pass 2 repeats the same sweep but stops before the sorted 8: it fixes [2, 5, 1, 4] into [2, 1, 4, 5]. Pass 3 yields [1, 2, 4] in place, and one more pass confirms nothing moves.

// note

Watch for this in the visualizer: the bars at the right end settle and stop being touched, one per pass. The shrinking "active zone" is Bubble Sort's only optimization.

The pseudocode

for i from 0 to n-1:
  swapped = false
  for j from 0 to n-i-2:
    if array[j] > array[j+1]:
      swap(array[j], array[j+1])
      swapped = true
  if not swapped:
    break   // already sorted — stop early

Two details matter. The inner loop bound n-i-2 is the shrinking active zone: pass i skips the i elements already locked in at the end. And the swapped flag gives Bubble Sort its one genuinely good property — if a full pass makes no swaps, the array is sorted and the algorithm stops immediately.

Why Bubble Sort is O(n²)

Count the comparisons. The first pass makes n−1 comparisons, the second n−2, and so on down to 1. That sum is n(n−1)/2, which grows like . Sorting 10 items takes ~45 comparisons; sorting 1,000 items takes ~500,000. Double the input and you quadruple the work — that is the signature of a quadratic algorithm.

CaseTimeWhat it means
Best (already sorted)O(n)One pass, zero swaps, early exit via the swapped flag
Average (random order)O(n²)Roughly n²/4 swaps — every inversion must be fixed one neighbour-swap at a time
Worst (reverse sorted)O(n²)Every comparison triggers a swap; maximum possible work
SpaceO(1)Sorts in place — only a temp variable for swapping

The deeper reason Bubble Sort is slow: it only ever moves elements one position at a time. An element that belongs 100 slots away needs 100 separate swaps to get there. Algorithms like Quick Sort and Merge Sort win because a single operation can move an element a long distance.

When is Bubble Sort actually fine?

  • Teaching and learning — it is the clearest possible introduction to comparison sorting, invariants, and Big-O analysis.
  • Nearly-sorted data — with the early-exit flag, a sorted or almost-sorted array is verified in a single O(n) pass.
  • Tiny inputs — for a handful of elements, the constant-factor simplicity beats the overhead of cleverer algorithms (though Insertion Sort is still usually better here).
  • Detecting sortedness — one bubble pass with no swaps is a proof the array is sorted.

For everything else, reach for an O(n log n) algorithm. If you are curious how much faster that actually is on real arrays, race them: the compare mode runs Bubble Sort against Quick Sort on identical data, side by side, and the difference is brutal even at 30 elements.

Bubble Sort vs its simple siblings

AlgorithmAverage timeSwapsStable?Best use
Bubble SortO(n²)O(n²) — manyYesTeaching; sortedness checks
Selection SortO(n²)O(n) — fewNoWhen writes are expensive
Insertion SortO(n²)O(n²)YesSmall or nearly-sorted arrays

All three are quadratic, but they fail differently. Selection Sort always scans the whole remaining array but makes at most n−1 swaps. Insertion Sort does the least work on nearly-sorted input and is the one of the three that survives in production (as the base case inside hybrid sorts like Timsort). Bubble Sort has the best early-exit behaviour but the worst swap count.

Common misconceptions

  • "Bubble Sort and Selection Sort are the same." No — Bubble Sort swaps neighbours continuously; Selection Sort finds the minimum first and makes exactly one swap per pass.
  • "It is called Bubble Sort because small elements bubble to the front." In the standard left-to-right version, it is the *large* elements that bubble to the *end* — small elements crawl left only one slot per pass (they are sometimes called "turtles").
  • "O(n²) means it always takes n² steps." Big-O is an upper-bound growth rate, not a step count — with the early-exit flag, sorted input finishes in one pass.

Try it yourself

Reading about sorting is like reading about swimming — at some point you have to get in the water. Run Bubble Sort on a random array, then on a reverse-sorted one, and watch the pseudocode highlight each comparison as it happens. Then race it against Quick Sort and feel the O(n²) pain viscerally.

Every comparison, swap, and pass — animated with synchronized pseudocode, playback controls, and adjustable speed.

Visualize Bubble Sort step by step

Visualize These Algorithms

Keep Reading