Skip to main content
Beginner ~10 min read

Bubble Sort

The friendly introduction to sorting: swap adjacent out-of-order pairs until everything bubbles into place.

Prerequisites: Arrays: Traversal, Insertion & Deletion, Big O Notation & Time Complexity

Bubble sort sweeps through the array comparing neighbors; whenever a pair is out of order, it swaps them. After the first sweep, the largest element has bubbled to the last position, it's guaranteed, because wherever the max starts, it wins every neighbor comparison it meets. Second sweep puts the second-largest second-from-last, and so on. The sorted region grows from the right.

It's the first sorting algorithm you should learn because every idea in sorting analysis appears: invariants (the tail is final after pass k), best/average/worst cases, and the difference between comparisons (always ~n²/2) and swaps (0 to n²/2). It's also the last algorithm you should ship: its O(n²) comparisons make it 100× slower than merge sort at n = 10,000, teachers use it because it's transparent, not because it's good.

One full trace: [5, 1, 4, 2]

  1. 1

    Pass 1

    5>1 swap → [1,5,4,2]; 5>4 swap → [1,4,5,2]; 5>2 swap → [1,4,2,5]. Largest (5) is now final at the end. 3 comparisons, 3 swaps.

  2. 2

    Pass 2

    1≤4 keep; 4>2 swap → [1,2,4,5]. 4 is final. 2 comparisons, 1 swap.

  3. 3

    Pass 3

    1≤2 keep. 1 comparison, 0 swaps, no swaps means fully sorted, stop early.

  4. 4

    Total

    6 comparisons, 4 swaps. Worst case would be 6 comparisons too (3+2+1), quadratic regardless of data.

Implementation with early exit

bubble-sort.js
// Pure: returns a new sorted array. Stable.
function bubbleSort(input) {
  const arr = [...input];
  const n = arr.length;
  for (let pass = 0; pass < n - 1; pass++) {
    let swapped = false;
    for (let i = 0; i < n - 1 - pass; i++) {   // tail [n-1-pass..] already final
      if (arr[i] > arr[i + 1]) {
        [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
        swapped = true;
      }
    }
    if (!swapped) break;   // early exit: a clean pass proves sortedness
  }
  return arr;
}
Operation / caseCostNotes
Best case (sorted input)O(n)early exit after one clean pass
Average & worst caseO(n²)~n²/2 comparisons
Swaps (worst)O(n²)reversed input
SpaceO(1)in-place, swaps neighbors
Stable?Yesequal elements never jump over each other

Check your understanding

  1. 1.After pass 1 of bubble sort, what is guaranteed?
  2. 2.Why does the inner loop shrink each pass (i < n - 1 - pass)?
  3. 3.Bubble sort on [2, 1, 3, 4, 5] takes how many swaps?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Visualize it

Bubble Sort

Play, pause, and scrub the real algorithm step by step.

Play it

Sorting Arena

Sort the bar array yourself using swaps, then find out how your move count compares to the theoretical minimum…

Keep going