Edexcel International Advanced Level Computer Science, point 10.3.3
This is the coding side of the bubble sort in 5.2.3. In Unit 2 you may need to amend and write it, with three versions of increasing efficiency.
a. Worst case (no improvements)
Always does every pass and compares every neighbouring pair on every pass.
def bubble_sort_worst(items):
n = len(items)
for _ in range(n - 1): # n - 1 passes
# compare every neighbouring pair
for i in range(n - 1):
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
return items
- passes, each with comparisons, so comparisons, whatever the data (16 for ).
- It is correct but wasteful: it keeps going after the list is sorted, and re-checks items that are already in place.
b. Exit when a pass makes no swaps
If a whole pass makes no swaps, the list is already sorted, so stop. Use a flag (a Boolean variable).
def bubble_sort_exit(items):
n = len(items)
swapped = True
while swapped:
swapped = False
for i in range(n - 1):
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
swapped = True
return items
swappedis set toFalseat the start of each pass, andTruewhenever a swap happens.- If it's still
Falseat the end of a pass, the loop ends. - Best case (already sorted): one pass, comparisons.
c. Reduce the upper bound on each pass
After pass 1, the largest item is in its final place at the end. After pass 2, the two largest are in place, and so on. So each pass can stop one place earlier.
def bubble_sort(items):
n = len(items)
swapped = True
while swapped and n > 1:
swapped = False
for i in range(n - 1):
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
swapped = True
n = n - 1 # the last item is now in place
return items
n = n - 1shortens each pass, so no time is wasted on sorted items.- This version combines both improvements.
Comparing the three
Number of comparisons (counted by running the code):
| List | (a) Worst | (b) Exit on no swaps | (c) Exit and reduce bound |
|---|---|---|---|
[5, 2, 9, 1] |
9 | 12 | 6 |
[1, 2, 3, 4, 5] (sorted) |
16 | 4 | 4 |
[1, 2, 3, 5, 4] (nearly sorted) |
16 | 8 | 7 |
[5, 4, 3, 2, 1] (reversed) |
16 | 20 | 10 |
Notes:
- For a sorted list, (b) and (c) need only one pass.
- Version (b) can do more comparisons than (a) on some lists (such as
[5, 2, 9, 1]and the reversed list), because (a) stops after passes but (b) needs an extra pass to find that nothing changed. - Version (c) is never worse than the others here, since it cuts each pass short.
Counting comparisons and swaps in code
def bubble_sort_counted(items):
n = len(items)
comparisons = swaps = 0
swapped = True
while swapped and n > 1:
swapped = False
for i in range(n - 1):
comparisons += 1
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
swaps += 1
swapped = True
n -= 1
return items, comparisons, swaps
print(bubble_sort_counted([5, 2, 9, 1])) # ([1, 2, 5, 9], 6, 4)
Other variations
- The order: the comparison in the
ifdecides the order, so reversing the comparison reverses the sort. - Sorting a list of strings or records: compare the right field (for products sorted by price:
items[i]["price"] > items[i + 1]["price"]). - Sorting in place (as above) or returning a new sorted list (copy first with
items = items[:]).
Testing
tests = [[], [1], [2, 1], [3, 3, 3], [5, 2, 9, 1],
[1, 2, 3], [3, 2, 1], [4, -2, 0]]
for t in tests:
assert bubble_sort(t[:]) == sorted(t)
print("All bubble sort tests passed")
Include empty, one item, already sorted, reversed, duplicates, and negative numbers.
Worked example
Task: trace version (c) on [4, 3, 1, 2], and say how many comparisons it makes.
| Pass | n (range) |
Comparisons | List after | Swapped? |
|---|---|---|---|---|
| 1 | 4 | 4 and 3 swap; 4 and 1 swap; 4 and 2 swap (3 comparisons) | [3, 1, 2, 4] |
Yes |
| 2 | 3 | 3 and 1 swap; 3 and 2 swap (2 comparisons) | [1, 2, 3, 4] |
Yes |
| 3 | 2 | 1 and 2 in order (1 comparison) | [1, 2, 3, 4] |
No: stop |
Total: 3 + 2 + 1 = 6 comparisons and 5 swaps. Version (a) would make 9 comparisons.
Exam tip: know all three versions and what each improvement saves. Set swapped = False at the start of each pass, not before the loop only. Reducing the bound works because the largest items are already in place. A common error is an off-by-one in range(n - 1), so that items[i + 1] goes out of range.
Check yourself
How many comparisons does the worst-case bubble sort make on 6 items?
(6 − 1)² = 25.
What is the purpose of the swapped flag?
It records whether a pass made any swaps; if not, the list is sorted and the loop can stop.
Why can the upper bound be reduced after each pass?
The largest remaining item is in its final place at the end after each pass, so it doesn't need to be compared again.
How many comparisons does the improved sort need for a list that is already sorted, with 8 items?
7 (one pass).