Sub topic 4
Stopping Early When a Pass Makes No Swaps
This chapter assumes you have read the bubble sort chapter. You should be able to trace a pass by hand, and you should know that after pass i the last i + 1 positions hold their final values. You should also be comfortable with Big-O notation and with counting comparisons and swaps as defined in the cost model chapter.
Plain bubble sort always runs n - 1 passes, even when the array was sorted before the first pass. The fix is small. Keep a flag that records whether the current pass swapped anything, and stop as soon as a pass finishes with no swaps. This chapter explains why that test is safe, what it saves, what it does not save, and the mistakes people make when they add it.
The Swapped Flag
Here is bubble sort with the early-exit test:
def bubble_sort(a):
n = len(a)
for i in range(n - 1):
swapped = False
# 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]
swapped = True
if not swapped:
break
return a
print(bubble_sort([5, 1, 4, 2, 8])) # [1, 2, 4, 5, 8]Two lines carry the optimization. swapped = False resets the flag at the start of every pass. if not swapped: break checks it after the inner loop has finished the whole pass. Both placements matter, and the section on common errors shows what goes wrong when either line moves.
Why a Swap-Free Pass Proves the Array Is Sorted
The early exit is only correct if a pass with no swaps guarantees the array is sorted. The argument has two parts.
- The unsorted prefix is in order. Pass
icompares every adjacent pair ina[0 .. n-1-i]. No swap meansa[j] <= a[j+1]for every one of those pairs. A chain of adjacent<=relations means the whole prefix is non-decreasing. - The suffix is already final. By the bubble sort invariant,
a[n-i .. n-1]holds theilargest values in sorted order. Each of them is at least as large as anything in the prefix.
A sorted prefix followed by a sorted suffix of larger values is a sorted array, so stopping cannot give a wrong answer. The proof needs only the comparisons the pass actually made, so it holds for any input, including inputs with duplicates.
Measuring What the Flag Saves
The function below counts passes, comparisons, and swaps, with and without the early exit, on five-element inputs that have different shapes:
def bubble_stats(data, early_exit=True):
a = list(data)
n = len(a)
passes = comparisons = swaps = 0
for i in range(n - 1):
passes += 1
swapped = False
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
swapped = True
if early_exit and not swapped:
break
return passes, comparisons, swaps
cases = {
"sorted": [1, 2, 3, 4, 5],
"one swap": [1, 2, 3, 5, 4],
"rabbit": [5, 1, 2, 3, 4],
"turtle": [2, 3, 4, 5, 1],
"reversed": [5, 4, 3, 2, 1],
}
for name, data in cases.items():
print(name, bubble_stats(data, early_exit=False), bubble_stats(data, early_exit=True))The output, arranged as a table, shows (passes, comparisons, swaps):
| Input | Without early exit | With early exit |
|---|---|---|
| sorted `[1,2,3,4,5]` | (4, 10, 0) | (1, 4, 0) |
| one swap `[1,2,3,5,4]` | (4, 10, 1) | (2, 7, 1) |
| rabbit `[5,1,2,3,4]` | (4, 10, 4) | (2, 7, 4) |
| turtle `[2,3,4,5,1]` | (4, 10, 4) | (4, 10, 4) |
| reversed `[5,4,3,2,1]` | (4, 10, 10) | (4, 10, 10) |
The table shows three things:
- Swaps never change. The flag skips only passes that would have made no swaps, so the swap count is identical in both columns. Only comparisons and passes go down.
- Sorted input becomes linear. One pass of
n - 1comparisons confirms the order and the loop exits. The best case drops from Θ(n²) to Θ(n). - The worst case does not move. Reversed input still needs every pass, which is n(n − 1)/2 comparisons.
Rabbits and Turtles
The "rabbit" and "turtle" rows have the same swap count, but only the rabbit benefits from the flag. The difference comes from how far a single pass can move an element in each direction.
- A large element far to the left (a rabbit) is carried right in one pass, because the comparison keeps winning and the element keeps moving. In
[5, 1, 2, 3, 4]the 5 reaches the end in pass 1, and pass 2 confirms the array is sorted. - A small element far to the right (a turtle) moves left only one position per pass, because it takes part in just one swap each pass. In
[2, 3, 4, 5, 1]the 1 needs four passes to reach index 0.
This gives an exact pass count. Let d be the largest distance any element must travel to the left, meaning its starting index minus its final index. For n >= 2, bubble sort with early exit runs:
passes = min(d + 1, n - 1)
It needs d passes to bring the worst turtle home and one more pass to see that nothing moved. If d is already n - 1, the outer loop ends on its own before the confirming pass. Check it against the table: the rabbit has d = 1 (the 1 moves from index 1 to 0), giving 2 passes. The turtle has d = 4, giving min(5, 4) = 4.
Cocktail shaker sort is a variant that alternates left-to-right and right-to-left passes so that turtles also move quickly. It improves particular inputs, but its worst case is still quadratic. It is a patch on bubble sort rather than a reason to choose it.
A Tighter Bound: Remember Where the Last Swap Happened
The flag throws away useful information. If the last swap in a pass happened at index last, then no pair from last + 1 onward was out of order. The running maximum that the pass carried right also landed at last + 1. So every position after last is final, often more of them than the i + 1 positions the basic invariant promises. The next pass only needs to compare pairs up to (last - 1, last).
def bubble_sort_last_swap(a):
bound = len(a) - 1 # compare pairs (j, j+1) for j < bound
while bound > 0:
last = 0
for j in range(bound):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
last = j
bound = last # everything after index last is final
return a
print(bubble_sort_last_swap([3, 1, 2, 7, 8, 9])) # [1, 2, 3, 7, 8, 9]This version needs no separate flag. A pass with no swaps leaves last = 0, which sets bound = 0 and ends the loop. A pass whose only swap was at j = 0 also ends the loop, which is correct: after that pass, a[1:] is final and a[0] is the minimum. On [3, 1, 2, 7, 8, 9] the first pass makes its last swap at j = 1, so the second pass compares only the pair (0, 1) and the loop stops. That totals 6 comparisons, compared with 5 + 4 = 9 for the flag version.
The asymptotic picture stays the same. The best case is Θ(n), the worst case is Θ(n²), and turtles are still slow. The gain is a constant factor on inputs whose tail becomes sorted early.
Edge Cases
| Input | Behavior with early exit |
|---|---|
| Empty list | `range(-1)` is empty, so there are zero passes |
| One element | `range(0)` is empty, so there are zero passes |
| All elements equal | One pass with `n - 1` comparisons and no swaps, then exit |
| Already sorted | One pass with `n - 1` comparisons, then exit |
| Reverse sorted | All `n - 1` passes; the flag never fires |
The all-equal row depends on the strict > comparison. With >=, equal neighbors get swapped, so the flag is set on every pass that contains equal adjacent values. The early exit then never fires on input like [2, 2, 2, 2], and the sort also stops being stable. The stability chapter covers that second effect.
Common Errors
- Resetting the flag once instead of every pass. If
swapped = Falsesits above the outer loop, the flag staysTrueafter the first swap and the early exit never fires again. The sort is still correct, but the optimization is silently gone. Every test passes, so this bug is easy to miss. Measure the pass count on sorted input to catch it. - Breaking inside the inner loop. Putting
if not swapped: breakinside thefor jloop stops the pass at the first pair that is in order. The result is often unsorted. The check belongs after the inner loop. - Exiting when a pass swaps exactly once. One swap can create a new out-of-order pair to its left. For example,
[2, 3, 1]becomes[2, 1, 3]. Only a pass with zero swaps proves the array is sorted. - Dropping the shrinking bound because the flag "replaces" it. The flag and the
n - 1 - ibound do different jobs. Without the bound, every pass rescans the finished tail. The result is still correct, but each pass does extra comparisons. - Calling bubble sort adaptive like insertion sort. With the flag, bubble sort is adaptive only to how far elements must travel left. Insertion sort adapts to the total number of inversions, which is a weaker condition to meet.
Exercise
Using bubble_sort with the swapped flag, how many passes and comparisons does it make on [1, 2, 3, 4, 5, 6, 0]? Explain using the leftward-distance formula.
Show answer
The 0 must move from index 6 to index 0, so d = 6 and n - 1 = 6. The formula gives passes = min(7, 6) = 6, which is every pass. Comparisons are 6 + 5 + 4 + 3 + 2 + 1 = 21, the same as without the flag. This input is a turtle, so the early exit saves nothing.
Exercise
A colleague moves "swapped = False" above the outer for loop. On [1, 3, 2, 4, 5, 6], how many passes run before and after this change?
Show answer
Correct version: pass 1 swaps 3 and 2 and sets the flag, pass 2 makes no swaps and exits, so 2 passes. Buggy version: the flag becomes True in pass 1 and is never reset, so all n - 1 = 5 passes run. The output is sorted in both cases, which is why the bug passes correctness tests.
Exercise
Trace bubblesortlast_swap on [4, 1, 2, 3, 9, 10]. List the bound before each pass and the total comparisons.
Show answer
Pass 1 runs with bound 5. Swaps happen at j = 0, 1, and 2 (the 4 moves right to index 3). No swaps happen at j = 3 or 4, so last = 2 and the array is [1, 2, 3, 4, 9, 10]. Pass 2 runs with bound 2 and makes no swaps, so last = 0 and the loop ends. The total is 5 + 2 = 7 comparisons. The flag version would use 5 + 4 = 9.