Sub topic 3
Bubble Sort: Swapping Adjacent Pairs Until the Largest Values Settle
This chapter assumes you can write loops over list indices in Python and read Big-O notation. It also uses the cost model from the previous chapter, which counts comparisons and swaps separately.
The Idea
Bubble sort makes repeated passes over the array. Each pass compares every pair of neighbors, a[j] and a[j + 1]. When a pair is out of order, the two values swap. A large value keeps winning these comparisons, so it travels right on every step until it reaches its final position. That movement is where the name comes from: the largest values "bubble up" to the end.
After the first pass, the maximum sits in the last slot. After the second pass, the second-largest sits next to it. In general, after pass i (counting from 0), the last i + 1 positions hold their final values. Each new pass can therefore stop one position earlier than the one before.
The Code
This version shrinks the inner range after each pass. The next chapter adds the early-exit check.
def bubble_sort(a):
n = len(a)
for i in range(n - 1):
# After pass i, the last i + 1 positions hold their final values.
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
return a
print(bubble_sort([5, 1, 4, 2, 8])) # [1, 2, 4, 5, 8]The sort is in place. It needs only a constant amount of extra memory: the loop counters and the temporary value that tuple assignment uses during a swap.
Tracing It by Hand
Here is the trace for [5, 1, 4, 2, 8], with n = 5:
| Pass i | j range | Array after pass | Comparisons | Swaps |
|---|---|---|---|---|
| 0 | 0 to 3 | [1, 4, 2, 5, 8] | 4 | 3 |
| 1 | 0 to 2 | [1, 2, 4, 5, 8] | 3 | 1 |
| 2 | 0 to 1 | [1, 2, 4, 5, 8] | 2 | 0 |
| 3 | 0 | [1, 2, 4, 5, 8] | 1 | 0 |
Pass 0 moves the 5 right three times: past the 1, the 4, and the 2. It stops at the 8 because 5 < 8. The 8 was already the maximum, so it stays put. From pass 2 on, the array is sorted, but this version keeps comparing anyway.
The comparison count is always (n−1) + (n−2) + … + 1 = n(n−1)/2, whatever the input. For n = 5 that is 10. The swap count depends on the input. It is 4 here, and it can be anywhere from 0 to n(n−1)/2. A later chapter explains exactly which property of the input sets that number.
Common Errors
- Index out of range. If the inner loop runs
for j in range(n - i), thena[j + 1]reads one slot past the end. The upper bound must ben - 1 - i. - Using
>=instead of>. The sort still produces sorted output, but it now swaps equal neighbors. That wastes swaps, and it breaks stability, which a later chapter covers. - Not shrinking the range. If the inner loop always uses
range(n - 1), the result is still correct. It just repeats comparisons against the tail that is already settled, about doubling the comparison count. - Expecting few passes on sorted input. Without an early-exit check, sorted input still costs n(n−1)/2 comparisons.
Exercise
Run the bubble_sort above on [4, 3, 2, 1]. How many comparisons and how many swaps does it make, and what does the array look like after pass 0?
Show answer
After pass 0 the array is [3, 2, 1, 4]. Pass 0 makes 3 swaps, pass 1 makes 2, and pass 2 makes 1, for 6 swaps in total. There are also 6 comparisons, since n(n−1)/2 = 4·3/2 = 6. Every comparison causes a swap, so reverse-sorted input is the worst case for swaps.
Exercise
A teammate writes the inner loop as for j in range(n - 1) with no - i. Is the output still sorted? What does the change cost for n = 1000?
Show answer
Yes, the output is still sorted, because extra comparisons against the settled tail never cause a swap. The cost is (n−1)·(n−1) = 998,001 comparisons instead of n(n−1)/2 = 499,500, which is roughly twice as many.