AlgoPlusAlgoPlus
Learn/Data Structures & Algorithms
Lesson

Bubble Sort

Repeatedly swap adjacent out-of-order pairs; each pass floats the next-largest value to the end.

7 min read Watch it move Build it

Bubble sort is the simplest sort to picture: walk the list comparing each pair of neighbours, and swap them whenever they're out of order. Like bubbles rising in liquid, the heaviest value 'sinks' to the right on every pass — so after enough passes, everything has settled into place. It's slow, but it's where almost everyone starts.

Why one pass settles one value

Sweep left to right comparing arr[i] with arr[i+1]. The largest value you meet keeps winning its comparisons and gets carried along until it reaches the far right — so one full pass guarantees the maximum lands in its final spot. The next pass only needs to reach one position earlier, and so on.

  1. 1Compare the first two elements; if the left is bigger, swap them.
  2. 2Step right and repeat for every adjacent pair to the end of the unsorted region.
  3. 3After the pass, the largest unsorted value has bubbled to its final place — shrink the region by one.
  4. 4Repeat the passes until no swaps are needed.
The early-exit trick
If a whole pass makes zero swaps, the list is already sorted — stop immediately. This single check is what makes bubble sort run in O(n) on already-sorted or nearly-sorted input.
function bubbleSort(arr) {
  for (let end = arr.length - 1; end > 0; end--) {
    let swapped = false;
    for (let i = 0; i < end; i++) {
      if (arr[i] > arr[i + 1]) {
        [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
        swapped = true;
      }
    }
    if (!swapped) break; // already sorted — early exit
  }
  return arr;
}
Why it's stable
Bubble sort only ever swaps strictly out-of-order neighbours. Equal values are never swapped past each other, so their original order is preserved — bubble sort is stable.
OperationTimeSpace
Best (sorted) · one clean pass, early exitO(n)O(1)
Average / worst · items move one step at a timeO(n²)O(1)
Check yourself
What does a single complete pass of bubble sort guarantee?