Lesson 32 · Core algorithms

Bubble Sort: Passes, Swaps and Complexity

The simplest comparison sort: walk the array, swap neighbours that are out of order, and repeat until a whole pass makes no swap.

Bubble Sort: Passes, Swaps and Complexity concept diagramA visual explanation of the layout and operations shown in this lesson.each pass walks the array and swaps adjacent values out of orderinput51428after pass 114258after pass 2124588 final8, 5 finalafter pass k the last k values are sorted — a pass with no swap means done
1

How a Pass Works

  1. Compare a[j] with a[j + 1], starting at j = 0
  2. If the left value is larger, swap them
  3. Move one place right and repeat until the end of the unsorted part
  4. The largest unsorted value is now last; shrink the unsorted part by one and start the next pass

Bubble sort sorts by comparing neighbours. It walks the array from left to right, and whenever a value is larger than the one after it, the two are swapped. One such walk is a pass.

The name comes from what a pass does to the largest value it meets. Once the walk reaches that value, it wins every comparison after it, so it is swapped forward again and again until it reaches the end of the unsorted part. It has bubbled to the top.

That gives the fact everything else rests on: after pass k, the last k positions hold the k largest values in sorted order, and they never move again. So pass k + 1 can stop one comparison earlier than pass k, which is what the inner loop bound n - 1 - i does in the code below.

  • A pass compares every neighbouring pair in the unsorted part, once
  • Each pass fixes at least one value in its final place
  • The sorted part grows from the right end
  • Small values move left only one place per pass
2

Passes, Comparisons and Swaps

The plain version always makes n − 1 passes. Pass 1 makes n − 1 comparisons, pass 2 makes n − 2, down to 1, so the total is n(n − 1)/2, which is O(n²). For n = 1,000 that is 499,500 comparisons, where merge sort needs under 10,000.

The number of swaps is fixed by the input, not by the loops. An inversion is a pair of values in the wrong order, such as 5 before 2. Swapping two neighbours that are out of order fixes exactly that one pair and leaves every other pair as it was, so the number of swaps equals the number of inversions. [5, 1, 4, 2, 8] has 4 inversions, (5,1), (5,4), (5,2) and (4,2), and bubble sort makes exactly 4 swaps on it.

The number of passes in bubble sort with the early exit is one more than the largest number of places any value has to move left, capped at n − 1. A value moves left at most one place per pass, so a small value at the far right sets the count. In [5, 1, 4, 2, 8], the 2 must move 2 places, so the sort takes 2 passes with swaps plus 1 clean pass: 3 passes and 4 + 3 + 2 = 9 comparisons.

How the input order changes the work (with the early-exit flag)
InputPassesComparisonsSwaps
Already sorted1n − 10
Random orderclose to n − 1close to n²/2n(n − 1)/4 on average
Reverse sortedn − 1n(n − 1)/2n(n − 1)/2
  • Worst and average time O(n²); best O(n) with the flag
  • Swaps always equal the inversions in the input
  • Extra space O(1): every swap happens inside the array
  • Reverse order is the worst case: every pair is an inversion
3

The Early-Exit Flag

The plain version keeps sweeping after the array is already sorted, because nothing tells it to stop. Optimized bubble sort adds one boolean, swapped, set to false at the start of each pass and to true on every swap. If a whole pass ends with it still false, no neighbouring pair is out of order, which means the array is sorted, so the loop breaks.

On sorted input this turns n(n − 1)/2 comparisons into n − 1: one clean pass and done. [1, 2, 3, 4, 5] costs 4 comparisons instead of 10. On reversed input the flag never helps, since every pass swaps something.

A second, smaller improvement remembers where the last swap of a pass happened. Nothing after that point moved, so it is already in its final order, and the next pass can stop there instead of only one place earlier. It never changes the worst case, but it cuts passes over a sorted tail.

  • Reset swapped at the top of every pass, not once before the loop
  • A clean pass is proof: no neighbour is out of order, so no pair is
  • Best case: n − 1 comparisons and 0 swaps
  • Worst and average cases stay O(n²)
Key reference

Terms, operations, and practical uses

Core mechanics

  • PassOne left-to-right walk comparing each neighbouring pair in the unsorted part.
  • BubblingThe largest unsorted value winning every comparison and being swapped to the end of the pass.
  • Swapped flagA boolean that records whether a pass swapped anything; false at the end means sorted.

Properties

  • StableOnly strictly greater values are swapped, so equal keys never cross.
  • AdaptiveWith the flag, sorted input costs one pass of n − 1 comparisons.
  • In placeO(1) extra space; every swap happens inside the array.

Counting

  • InversionA pair of values in the wrong order; each swap removes exactly one.
  • TurtleA small value near the end, which moves left only one place per pass.
  • Cocktail shaker sortThe two-way variant that moves turtles home in one backward sweep.
Implementation

Code in Python, C++ and Java

def bubble_sort(values):
    n = len(values)
    for i in range(n - 1):
        swapped = False
        # the last i entries are already final, so stop early
        for j in range(n - 1 - i):
            if values[j] > values[j + 1]:
                values[j], values[j + 1] = values[j + 1], values[j]
                swapped = True
        if not swapped:
            # a clean pass means the array is sorted
            break
    return values


print(bubble_sort([5, 1, 4, 2, 8]))
#include <iostream>
#include <vector>

void bubbleSort(std::vector<int>& values) {
    const int n = static_cast<int>(values.size());
    for (int i = 0; i < n - 1; ++i) {
        bool swapped = false;
        // the last i entries are already final, so stop early
        for (int j = 0; j < n - 1 - i; ++j) {
            if (values[j] > values[j + 1]) {
                std::swap(values[j], values[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break;     // a clean pass means the array is sorted
    }
}

int main() {
    std::vector<int> values{5, 1, 4, 2, 8};
    bubbleSort(values);
    std::cout << '[';
    for (size_t i = 0; i < values.size(); ++i) std::cout << (i ? ", " : "") << values[i];
    std::cout << "]\n";
}
import java.util.Arrays;

public class Main {
    static void bubbleSort(int[] values) {
        int n = values.length;
        for (int i = 0; i < n - 1; i++) {
            boolean swapped = false;
            // the last i entries are already final, so stop early
            for (int j = 0; j < n - 1 - i; j++) {
                if (values[j] > values[j + 1]) {
                    int tmp = values[j];
                    values[j] = values[j + 1];
                    values[j + 1] = tmp;
                    swapped = true;
                }
            }
            if (!swapped) break; // a clean pass means the array is sorted
        }
    }

    public static void main(String[] args) {
        int[] values = {5, 1, 4, 2, 8};
        bubbleSort(values);
        System.out.println(Arrays.toString(values));
    }
}
Watch it run

Step through it

Running on [5, 1, 4, 2, 8]

pass 1, j = 0beforeafter51428154285 > 1: swappass1comparisons1swaps1swappedtrueinversions left: (5,4) (5,2) (4,2)
Step 1

Pass 1: compare 5 and 1

The walk starts at the left. 5 > 1, so the pair is out of order and the two swap: 5 moves right, 1 moves left. That swap fixes the inversion (5,1) and touches no other pair, so 3 inversions are left.

Output
1 / 13
4

Stability, Turtles and Edge Cases

Bubble sort is stable: two equal values keep their original order. That holds only because the test is strictly >. Change it to >= and equal neighbours are swapped, so [2a, 2b, 1] finishes as [1, 2b, 2a] and the order of the two 2s is lost.

Large values move right fast, one pass carries a value all the way. Small values at the right end move left only one place per pass. Those slow values are called turtles: [2, 3, 4, 5, 1] is almost sorted, yet the 1 needs 4 passes to reach the front. Cocktail shaker sort fixes this by sweeping left to right and then right to left in turn, so a turtle is carried home in one backward sweep.

The edge cases are easy to check against the code. An empty array or one element makes no comparison, since the outer loop runs n − 1 = 0 times or fewer. An array of equal values makes one clean pass. Negative numbers and duplicates need nothing special.

  • Use >, never >=, or the sort stops being stable
  • A small value at the end costs one pass per place it must move
  • Cocktail shaker sort sweeps both ways to move turtles quickly
  • 0 or 1 element: no comparisons, nothing to do
5

Where Bubble Sort Stands

Bubble sort against insertion sort is the comparison that matters, because both are simple, stable, in place and O(n²). Both also do work equal to the number of inversions. The difference is cost per step: insertion sort shifts a value left with one write per place and stops as soon as it finds its spot, while bubble sort pays a three-step swap per place and keeps comparing to the end of each pass. On random input insertion sort makes about n²/4 comparisons against bubble sort's n²/2.

Selection sort is the other classroom sort. It makes the same n(n − 1)/2 comparisons whatever the input, but at most n − 1 swaps, which helps only when writing is expensive. For real work, merge sort and quick sort run in O(n log n).

Bubble sort earns its place as a teaching tool: it is the clearest example of a loop invariant (the sorted tail grows by one each pass). One pass of it is also a cheap O(n) check that an array is already sorted. For a sorting problem to practise on, Sort Colors shows how much faster a sort can be when the values are known in advance.

Bubble sort against insertion sort
Bubble sortInsertion sort
Comparisons, random inputabout n²/2about n²/4
Moves per out-of-order pairone swap (3 writes)one shift (1 write)
Sorted inputn − 1 comparisons, with the flagn − 1 comparisons
Stable, in placeyesyes
  • Insertion sort does the same inversion count of moves, more cheaply
  • Selection sort writes least but never finishes early
  • Bubble sort is for learning invariants and checking sortedness, not production