Sub topic 4
Stopping Early When a Pass Makes No Swaps
This chapter assumes you know the basic bubble sort from the previous chapter: each pass walks through the unsorted part of the array and swaps out-of-order neighbors, which pushes the largest remaining value to the end. You should also be comfortable reading Big-O notation and Python loops.
The wasted work in plain bubble sort
Plain bubble sort always runs n - 1 passes. It does this even when the array becomes sorted after the first pass, or was sorted from the start. On sorted input of length n, it still makes n(n-1)/2 comparisons and finds nothing to swap.
There is a simple signal that the work is finished. If a full pass makes no swaps, every adjacent pair in the unsorted region satisfies a[j] <= a[j + 1]. Because the tail is already in final position, the whole array is sorted. Any further pass would also make no swaps.
Adding the flag
The fix is one boolean per pass:
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]The flag resets at the start of each pass. If it is still False at the end of the pass, the loop stops.
Measuring the effect
This instrumented version counts passes and comparisons, so you can see where the flag helps:
def bubble_sort_stats(a):
a = list(a)
n = len(a)
passes = comparisons = 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]
swapped = True
if not swapped:
break
return passes, comparisons
for data in ([1, 2, 3, 4, 5, 6], [6, 1, 2, 3, 4, 5],
[2, 3, 4, 5, 6, 1], [6, 5, 4, 3, 2, 1]):
print(data, bubble_sort_stats(data))
# [1, 2, 3, 4, 5, 6] (1, 5)
# [6, 1, 2, 3, 4, 5] (2, 9)
# [2, 3, 4, 5, 6, 1] (5, 15)
# [6, 5, 4, 3, 2, 1] (5, 15)| Input (n = 6) | Passes | Comparisons | Without flag |
|---|---|---|---|
| Already sorted | 1 | 5 | 15 |
| Large value at front | 2 | 9 | 15 |
| Small value at end | 5 | 15 | 15 |
| Reversed | 5 | 15 | 15 |
The best case drops from O(n²) to O(n): one pass of n - 1 comparisons and zero swaps. The worst case stays O(n²).
Rabbits and turtles
The two middle rows look similar, but they behave very differently. A large value near the front is called a "rabbit". One pass carries it all the way to the end, so the sort finishes quickly. A small value near the end is called a "turtle". It moves left only one position per pass, so it needs about n - 1 passes, and the flag never fires early.
Common mistakes
- Setting
swapped = Falseonce, outside the outer loop. After the first swap the flag staysTrueforever and the early exit never happens. - Putting the
breakinside the inner loop. That stops the pass partway through and can leave the array unsorted. - Counting the check as free. Early exit removes passes, but every pass that does run still performs all of its comparisons.
Exercise
Using the early-exit bubble sort, how many passes and comparisons does it take to sort [1, 2, 3, 5, 4]?
Show answer
2 passes and 7 comparisons. Pass 1 makes 4 comparisons and swaps 5 and 4, so the array becomes sorted, but swapped is True. Pass 2 makes 3 comparisons with no swaps, so the loop exits.
Exercise
Give an input of length 5 on which the early-exit version makes exactly as many comparisons as plain bubble sort, without being in reverse order.
Show answer
[2, 3, 4, 5, 1]. The 1 is a turtle that moves left one position per pass, so every one of the 4 passes makes a swap. The sort makes 4 + 3 + 2 + 1 = 10 comparisons, the same as plain bubble sort.