Bubble Sort
Bubble sort puts a list in order by repeatedly comparing neighbouring elements and swapping any pair that is out of order. It is rarely the fastest choice. It is, however, the sorting algorithm you are most likely to trace by hand on a test, and a clean setting for learning to count the work an algorithm does. Throughout this lesson the goal is ascending order, and each pass scans from left to right.
How one pass works
A pass is one sweep through the unsorted part of the list. You compare positions 1 and 2, then 2 and 3, and so on, swapping whenever the left value is larger than the right. When the sweep meets the largest value of the unsorted part, that value wins every later comparison and is carried all the way to the end, the way a bubble rises to the surface. That gives the key invariant: after pass k, the k largest values sit in their final positions, so each new pass can stop one position earlier.
Example: Start with [6, 2, 9, 4, 3]. The pair 6, 2 is swapped, 6 and 9 stay where they are, then 9 is swapped past 4 and past 3. After four comparisons and three swaps the list is [2, 6, 4, 3, 9], and 9 never moves again.
If a whole pass makes no swaps, every adjacent pair is already in order, so the entire list is sorted. The early-exit version records this with a flag and stops:
def bubble_sort(a):
n = len(a)
for end in range(n - 1, 0, -1):
swapped = False
for i in range(end):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
if not swapped:
break
return aCounting comparisons and swaps
For a list of n elements, pass 1 makes n−1 comparisons, pass 2 makes n−2, and so on down to 1. When every pass is needed, the total is
Swaps follow a different rule. An inversion is a pair of values that appear in the wrong order relative to each other, whether or not they are next to each other. Swapping an adjacent out-of-order pair removes exactly one inversion and creates none, so the total number of swaps equals the number of inversions in the starting list. The list [3, 1, 2] contains two inversions, (3, 1) and (3, 2), so bubble sort sorts it with exactly two swaps.
The growth column below uses Big-O notation.
Input order | Comparisons (early exit) | Swaps | Growth |
|---|---|---|---|
Already sorted (best) | n−1 | 0 | O(n) |
Random order of distinct values (average) | close to n(n−1)/2 for large n | n(n−1)/4 on average | O(n2) |
Reverse sorted (worst) | n(n−1)/2 | n(n−1)/2 | O(n2) |
Strengths and limits
Bubble sort is in place and stable, and with the early exit it finishes in a single pass on a list that is already sorted. Its weakness is the quadratic worst case: a reversed list of 10,000 elements needs 49,995,000 comparisons. Small values near the end are also slow to move, because a value travels left by at most one position per pass. The list [2, 3, 4, 5, 1] needs four passes even though moving a single value would fix it.
What to remember
- Each pass compares adjacent pairs and carries the largest unsorted value to the end.
- Pass k makes n−k comparisons; all passes together make n(n−1)/2.
- The total number of swaps equals the number of inversions in the starting list.
- A pass with no swaps means the list is sorted, so the early-exit version stops.
- Best case O(n) with early exit; average and worst case O(n2).
Example: Tracing an early-exit bubble sort
A program sorts the list 4, 2, 1, 5, 3, 6 into ascending order with an early-exit bubble sort. Each pass compares adjacent pairs from left to right across the unsorted part and swaps a pair when the left value is larger. The unsorted part shrinks by one position after every pass, and the program stops after the first pass that makes no swaps.
a) Trace pass 1. Give the list after the pass and the number of swaps it makes.
Nothing is known to be in place yet, so pass 1 compares all five adjacent pairs.
- 4>2, swap. The list becomes ________.
- 4>1, swap. The list becomes ________.
- 4<5, no swap.
- 5>3, swap. The list becomes 2, 1, 4, 3, 5, 6.
- 5<6, no swap.
After pass 1 the list is 2, 1, 4, 3, 5, 6, and the pass made 3 swaps. The largest value, 6, holds the last position and is now treated as sorted.
b) Trace passes 2 and 3, and explain why the program stops after pass 3.
Pass 2 works on the first five positions, 2, 1, 4, 3, 5, so it makes ________ comparisons.
- 2>1, swap. The list becomes ________.
- 2<4, no swap.
- 4>3, swap. The list becomes 1, 2, 3, 4, 5, 6.
- 4<5, no swap.
Pass 2 made ________ swaps. The list happens to be sorted now, but the program cannot know that yet: a pass that made swaps may have left other pairs out of order.
Pass 3 works on the first four positions, making ________ comparisons: 1 and 2, 2 and 3, 3 and 4. Every pair is already in order, so the swapped flag stays false. A pass with no swaps proves that every adjacent pair is in order, so the program stops after pass 3 with the list 1, 2, 3, 4, 5, 6.
c) Find the total number of comparisons and swaps. How many comparisons does the early exit save compared with a version that always runs every pass?
Add the work pass by pass:
Check the swaps by counting inversions in the starting list 4, 2, 1, 5, 3, 6. The out-of-order pairs are (4, 2), (4, 1), (4, 3), (2, 1) and (5, 3), so there are ________ inversions, matching the five swaps.
A version without the early exit runs all five passes, so it makes ________ comparisons:
The early exit saves 15−12=3 comparisons. The swap count is 5 either way, because passes 4 and 5 would find no out-of-order pairs.
Match each bubble sort term with the description that fits it. Each description is used exactly once, and every description refers to sorting a list of values into ascending order.
A Boolean reset before each sweep and set when an exchange happens; if it stays false, the algorithm stops early
The positions at the end of the list that already hold their final values after k sweeps
Input in strictly decreasing order, which needs n(n − 1)/2 exchanges
One sweep through the unsorted part of the list, comparing each neighbouring pair in turn
Needs only a constant amount of extra memory beyond the list itself
A pair of positions i < j where the earlier value is larger than the later value
Swap flag
Worst case
Pass
In-place
Sorted tail
Inversion
Arrange the steps of one pass of an early-exit bubble sort that sorts a list into ascending order, from the first step of the pass to the decision made at its end.
Loading ordering steps…