Reading preferences
Concept

Bubble Sort

Compare neighbouring number cards, swap the ones in the wrong order, and see why a full pass helps.

sorting, bubble sort, adjacent swaps, early stopping, invariant

The neighbour-swap idea

Place number cards [5, 2, 4, 1] in a row. We want the smallest on the left. Look at 5 and 2: 5 is bigger, so exchange the cards. This exchange is a swap. Now look at the next pair. You only need to ask one question at a time: "Is the left number bigger than the right number?"

Bubble Sort repeatedly compares neighbouring values. If a pair is out of order, it swaps them. Small local corrections eventually produce a globally ordered list. It is a useful first algorithm because its movement is easy to inspect.

Why learn it and where it is useful

The job is to turn a messy row into an ordered row using a simple repeated rule. Bubble Sort lets you see how many small decisions can solve a larger problem. It is especially useful as a learning demonstration of comparisons and swaps.

Putting prices in order is a real use of sorting, but Bubble Sort is generally not the best method for a large shop catalogue. Its simplicity helps us learn; it does not make it fast for large lists.

Why a pass works

A pass is one left-to-right trip through the part we are still sorting. During that trip, a large number keeps moving right whenever its next neighbour is smaller. After the first full trip, the largest number has reached the end.

Compare the first two values and keep the larger on the right. Compare that right-hand value with the next one. The larger of everything seen so far again moves right. Continuing this process carries the largest remaining value to the end of the unsorted region.

This gives an invariant: after each completed pass, the suffix contains the largest values in their final sorted positions. Later passes need not inspect that suffix.

Here, "invariant" means a promise that stays true after every pass. "Suffix" means the right-hand part. The promise is: the marked right-hand numbers are already in their final places.

Trace a small input

Start with [5, 2, 4, 1].

PassAfter the passGuaranteed sorted suffix
1[2, 4, 1, 5][5]
2[2, 1, 4, 5][4, 5]
3[1, 2, 4, 5][2, 4, 5]

The remaining first value must also be correct: all other values have been placed and no elements have been removed.

See the reasoning

Try Bubble Sort one decision at a time

Goal: smallest → largest. Taller bars mean bigger numbers. This is a teaching demonstration, not live Python execution.

  • Compare
  • Move
  • Final place
  1. 5
    Slot 1Not final
  2. 2
    Slot 2Not final
  3. 4
    Slot 3Not final
  4. 1
    Slot 4Not final
  5. 3
    Slot 5Not final

Start

Our goal is smallest to largest. Each bar is one number; a taller bar means a larger number.

Python illustration

def bubble_sort(values):
    for end in range(len(values) - 1, 0, -1):
        swapped = False
        for index in range(end):
            if values[index] > values[index + 1]:
                values[index], values[index + 1] = (
                    values[index + 1], values[index]
                )
                swapped = True
        if not swapped:
            break
    return values

print(bubble_sort([5, 2, 4, 1]))

Prepared output — not live execution:

[1, 2, 4, 5]

end marks the last position in the unsorted prefix. range(end) compares indices up to end - 1 with their right neighbours, so the code never reads beyond the list. Empty and one-element lists perform no passes.

Early stopping and complexity

If you make a whole trip and exchange no cards, the row is already ordered. There is no reason to keep doing trips. On a backwards row, however, many exchanges and trips are needed.

The symbols below describe how that work grows: n is the number of cards, O(n) is roughly linear growth, and O(n²) is roughly square growth.

A complete pass with no swaps proves the remaining prefix is ordered. This early-stopping check gives O(n) best-case time for an already sorted list. Without the check, the usual fixed-pass version still makes quadratic comparisons even on sorted input.

The worst case makes (n - 1) + (n - 2) + ... + 1 comparisons, which is n(n - 1)/2, so worst-case time is O(n²). Average time under a random-order model is also O(n²). Auxiliary space is O(1).

Stability and limitations

The code swaps only on strict >. Equal-key values never cross, making this implementation stable. It mutates the input list in place.

Bubble Sort often makes many swaps and is usually a poor choice for large collections. Nearly sorted does not automatically mean one pass: a small value near the right end can move left by only one position per pass.

Next, Selection Sort chooses the next minimum directly rather than repeatedly correcting neighbouring pairs.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. After the first full left-to-right pass, what is guaranteed?
2. Why can we stop after a complete pass with no swaps?
3. Why does this implementation swap only when the left value is strictly greater?
4. What is the worst-case time of this implementation?

References and further reading