AlgoFrames

Bubble sort

Bubble sort compares neighbours and swaps them when out of order, so the largest values bubble to the end. The sorted suffix grows by one each pass.

The idea

Children line up by height. Each one may only swap with a neighbour who is shorter.

Nobody looks at the whole line. Repeated neighbour swaps still end with a sorted line, and that is bubble sort.

Intuition

Compare 5 and 1. The bigger one is on the left, so they swap.

One pass of neighbour swaps carries the largest value, 8, to the end.

The largest value wins every comparison it takes part in, so it keeps moving right until it reaches the end.

Each pass fixes one more value at the end. The sorted part grows by one.

Complexity

Reversed input needs n(n - 1)/2 comparisons, which is O(n²). Sorted input stops after one pass of n - 1.

Pass k makes n - k comparisons, and the sum 1 + 2 + … + (n - 1) is n(n - 1)/2. Early exit helps only when the input is already close to sorted.

Swaps happen inside the array. Only j and swapped are stored, so space is O(1).

Pitfalls

The inner loop must stop before j = n - p. One step further and a[j + 1] reads past the end.

Swap only when a[j] > a[j + 1]. With ≥, the equal values 3a and 3b trade places and the sort is no longer stable.

Variations

A small value near the end moves only one step left per pass. Cocktail shaker sort adds right-to-left passes to move it faster.

Insertion sort also moves values between neighbours. Each value stops as soon as it fits, so it does fewer comparisons.

Code

Pseudocode

n ← length of a
for pass ← 1 to n - 1
  swapped ← false
  for j ← 0 to n - pass - 1
    if a[j] > a[j + 1]
      swap a[j] and a[j + 1]
      swapped ← true
  if not swapped: stop
return a

Python

def bubble_sort(a):
    n = len(a)
    for p in range(1, n):
        swapped = False
        for j in range(n - p):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swapped = True
        if not swapped:
            break
    return a

JavaScript

function bubbleSort(a) {
  const n = a.length;
  for (let p = 1; p < n; p++) {
    let swapped = false;
    for (let j = 0; j < n - p; j++) {
      if (a[j] > a[j + 1]) {
        [a[j], a[j + 1]] = [a[j + 1], a[j]];
        swapped = true;
      }
    }
    if (!swapped) break;
  }
  return a;
}

Java

static void bubbleSort(int[] a) {
    int n = a.length;
    for (int p = 1; p < n; p++) {
        boolean swapped = false;
        for (int j = 0; j < n - p; j++) {
            if (a[j] > a[j + 1]) {
                int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp;
                swapped = true;
            }
        }
        if (!swapped) break;
    }
}

Cost at a glance

BestO(n)
AverageO(n²)
WorstO(n²)
SpaceO(1)
Stableyes
In-placeyes
Adaptiveyes

Practice problems (7)

State after one pass Warm-up

Bubble sort runs on [6, 2, 7, 3, 5]. Arrange the bars as they stand after the first pass.

Count swaps Warm-up

Bubble sort runs on [3, 5, 2, 4, 1]. Count the swaps it makes, first in pass 1 and then in total.

Implement bubble sort with early exit Standard

Sort nums in ascending order with bubble sort and return it.

Stop as soon as a pass makes no swaps: then the array is already sorted.

Array after k passes Standard

Run exactly k passes of bubble sort on nums and return the array. A pass walks left to right over the unsorted part and swaps each neighbouring pair that is out of order.

If k is at least n - 1, return the sorted array.

How many swaps? Standard

Return how many swaps bubble sort makes while sorting nums in ascending order. Equal values never swap.

Spot the bug: the last pair Standard

This bubble sort leaves some arrays unsorted. Click the line with the bug, then fix it.

Count passes until sorted Challenge

Bubble sort with early exit runs on [4, 5, 6, 1, 2, 3]. Predict how many passes it runs, counting the final pass that finds no swaps.

Try to answer without simulating every comparison.

Related topics

Next on the path: Selection sort