Sub topic 3
Bubble Sort: Swapping Adjacent Pairs Until the Largest Values Settle
This chapter assumes you can write loops and conditionals, index into a Python list, and read Big-O notation. It also uses the cost model from the previous chapter, which counts comparisons, swaps, shifts, and extra space separately.
Bubble sort is the simplest of the three elementary sorts to describe. It walks through the array, compares each pair of neighbors, and swaps them if they are out of order. One full walk is called a pass. After each pass, the largest value that is not yet in place has moved to the end of the unsorted region, the way a bubble rises to the surface. Repeat the passes and the array ends up sorted.
The core operation: compare and swap neighbors
Bubble sort only ever does one thing to the data. It looks at a[j] and a[j + 1], and if a[j] > a[j + 1], it exchanges them. It never compares or moves elements that are far apart. This restriction explains most of its behavior:
- Each swap fixes exactly one out-of-order pair, so the total number of swaps is fixed by the input. It does not depend on how cleverly you schedule the passes.
- A large value can travel many positions to the right in a single pass, because it wins every comparison it is part of and keeps getting carried along.
- A small value can move only one position to the left per pass, because it is swapped once and then the scan moves past it.
The asymmetry in the last two points matters for performance, and we come back to it below.
One pass in detail
During a pass, index j sweeps left to right across the unsorted region. The larger value of each pair always ends up at a[j + 1]. So at every step, a[j + 1] holds the maximum of everything scanned so far. When the sweep reaches the end of the region, that maximum sits in the last slot. Nothing to its right is unsorted, so it is in its final position.
Because each pass puts one more value in its final slot, the unsorted region shrinks by one each time. Pass i (counting from 0) only needs to scan indices 0 through n - 1 - i. After n - 1 passes, the last n - 1 slots are final, and the one remaining element at index 0 must be the smallest. The array is sorted.
The basic implementation
Here is bubble sort without the early-exit check, with counters added so you can see the work it does. The next chapter adds the early exit.
def bubble_sort_basic(a):
n = len(a)
comparisons = swaps = 0
for i in range(n - 1):
# The last i positions are already final; scan only a[0..n-1-i].
for j in range(n - 1 - i):
comparisons += 1
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swaps += 1
return comparisons, swaps
data = [5, 1, 4, 2, 8]
print(bubble_sort_basic(data), data) # (10, 4) [1, 2, 4, 5, 8]The function sorts in place. It uses O(1) extra space: two loop indices and the temporary storage that Python's tuple swap uses for the exchange.
Tracing bubble sort by hand
Trace [5, 1, 4, 2, 8] with n = 5. Brackets mark the pair being compared, and a bar marks the start of the final region.
| Pass | Comparison | Before | Swap? | After | Column |
|---|---|---|---|---|---|
| 1 | j=0 | [5, 1], 4, 2, 8 | yes | 1, 5, 4, 2, 8 | |
| 1 | j=1 | 1, [5, 4], 2, 8 | yes | 1, 4, 5, 2, 8 | |
| 1 | j=2 | 1, 4, [5, 2], 8 | yes | 1, 4, 2, 5, 8 | |
| 1 | j=3 | 1, 4, 2, [5, 8] | no | 1, 4, 2, 5, \ | 8 |
| 2 | j=0 | [1, 4], 2, 5, 8 | no | 1, 4, 2, 5, 8 | |
| 2 | j=1 | 1, [4, 2], 5, 8 | yes | 1, 2, 4, 5, 8 | |
| 2 | j=2 | 1, 2, [4, 5], 8 | no | 1, 2, 4, \ | 5, 8 |
| 3 | j=0 | [1, 2], 4, 5, 8 | no | 1, 2, 4, 5, 8 | |
| 3 | j=1 | 1, [2, 4], 5, 8 | no | 1, 2, \ | 4, 5, 8 |
| 4 | j=0 | [1, 2], 4, 5, 8 | no | 1, \ | 2, 4, 5, 8 |
Notice two things in this trace. First, 5 moved three places right during pass 1, but 8 was already the maximum, so 5 stopped when it met 8. The value that settles at the end of a pass is the region's maximum, whatever value started the pass. Second, the array was sorted after pass 2, but the basic version still ran passes 3 and 4 and made 3 comparisons that changed nothing. Removing that waste is the topic of the next chapter.
You can print the state after each pass to check a hand trace:
def bubble_sort_trace(a):
n = len(a)
for i in range(n - 1):
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
print(f"after pass {i + 1}: {a} final from index {n - 1 - i}")
return a
bubble_sort_trace([5, 1, 4, 2, 8])
# after pass 1: [1, 4, 2, 5, 8] final from index 4
# after pass 2: [1, 2, 4, 5, 8] final from index 3
# after pass 3: [1, 2, 4, 5, 8] final from index 2
# after pass 4: [1, 2, 4, 5, 8] final from index 1Counting the work
The number of comparisons in the basic version depends only on n. Pass i makes n - 1 - i comparisons, so the total is
(n − 1) + (n − 2) + … + 1 = n(n − 1) / 2
For n = 5 that is 10, which matches the trace. The count is the same for sorted, random, and reversed input, so the basic version is Θ(n²) in comparisons in every case.
The number of swaps does depend on the input. Each swap exchanges an adjacent pair that is out of order. That removes exactly one inversion, meaning one pair of positions (p, q) with p < q and a[p] > a[q], and it creates no new inversions. Sorted input has zero inversions, so the number of swaps equals the number of inversions in the input. [5, 1, 4, 2, 8] has 4 inversions, (5,1), (5,4), (5,2), and (4,2), and the trace made 4 swaps. A later chapter builds on this link between swaps and inversions.
| Input (n elements) | Comparisons (basic) | Swaps |
|---|---|---|
| Already sorted | n(n − 1)/2 | 0 |
| Random order | n(n − 1)/2 | about n(n − 1)/4 on average |
| Reverse sorted | n(n − 1)/2 | n(n − 1)/2 |
Rabbits and turtles
The asymmetry noted at the start, where large values move far and small values move one step, has names. Large values near the front are rabbits: one pass carries them all the way to their final region. Small values near the back are turtles: each pass moves them only one position left.
Compare two inputs that each contain only one misplaced element:
def passes_until_sorted(a):
a = list(a)
n = len(a)
for i in range(n - 1):
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
if a == sorted(a):
return i + 1
return n - 1 if n > 1 else 0
print(passes_until_sorted([5, 1, 2, 3, 4])) # 1 (5 is a rabbit)
print(passes_until_sorted([2, 3, 4, 5, 1])) # 4 (1 is a turtle)Both inputs have 4 inversions, so both need 4 swaps. The rabbit case finishes all its swaps in the first pass. The turtle case spreads them over 4 passes, one per pass, because the 1 can move only one slot left each time. Even with early exit, the turtle case needs every pass. This is why bubble sort does poorly on input that is "nearly sorted" in the wrong way. Cocktail shaker sort fixes this by alternating left-to-right and right-to-left passes, which lets turtles move quickly on the backward passes. It does not change the O(n²) worst case.
(The a == sorted(a) check is only there to measure the pass count. It is not part of the algorithm.)
Common errors
- Off-by-one on the inner bound. Writing
for j in range(n - i)letsjreachn - 1on the first pass, soa[j + 1]raisesIndexError. The inner loop needs one fewer index than the region size, because it reads pairs. - Not shrinking the inner range. Writing
for j in range(n - 1)on every pass still sorts correctly, but it compares against the final region for no reason. That gives (n − 1)² comparisons instead of n(n − 1)/2. - Using
>=instead of>. This swaps equal neighbors. It adds pointless writes, and it reorders equal keys, which breaks the stability that bubble sort otherwise has. The stability chapter covers this in detail. - Assuming the array is sorted when one pass finishes. One pass guarantees only that the maximum is in place. The turtle example above shows you can need all n − 1 passes.
- Using
range(n)for the outer loop. The last pass then has an empty inner range. It is harmless, but it shows the author has not thought about when the work actually ends.
Where bubble sort stands
Bubble sort is correct, in place, and stable, and it is easy to verify. It is rarely the best choice. It makes as many element moves as insertion sort, but it does them with swaps rather than shifts, and its comparison count without early exit does not adapt to the input. Its main uses are teaching, very small fixed-size cases, and settings where only adjacent exchanges are allowed. Later chapters compare it directly with the other two sorts.
Exercise
Trace the basic bubble sort on [3, 2, 1]. Give the array after each pass, the total comparisons, and the total swaps.
Show answer
Pass 1 compares (3,2) and swaps to [2,3,1], then compares (3,1) and swaps to [2,1,3]. Pass 2 compares (2,1) and swaps to [1,2,3]. That is 3 comparisons and 3 swaps. The input is reversed, so it has 3(3 − 1)/2 = 3 inversions, and each swap removes one.
Exercise
A colleague writes for j in range(n - i) as the inner loop with for i in range(n - 1) as the outer loop. What happens on the first pass, and what is the fix?
Show answer
When i = 0, j runs up to n − 1, and a[j + 1] reads a[n], which raises IndexError. The inner loop must be range(n - 1 - i) so that the pair (j, j + 1) stays inside the unsorted region a[0..n-1-i].
Exercise
Without running code, how many passes does bubble sort need before [2, 3, 4, 5, 6, 1] becomes sorted, and how many swaps does it make in total? Explain using rabbits and turtles.
Show answer
It needs 5 passes and makes 5 swaps. The 1 is a turtle that has to move 5 positions left, and it moves exactly one position per pass. Its 5 inversions, one with each larger value, are removed by one swap per pass.
Exercise
Why does the basic bubble sort make exactly n(n − 1)/2 comparisons on an already sorted array, and what does this suggest about improving it?
Show answer
The loop bounds depend only on n. Pass i always makes n − 1 − i comparisons, whatever the values are, so the total is (n − 1) + … + 1 = n(n − 1)/2. On sorted input, the first pass makes no swaps, which proves the array is already sorted. Stopping at that point would make the best case O(n). The early-exit optimization does exactly this.