Bubble sort and selection sort
Bubble sort swaps out-of-order neighbours so each pass carries the largest to the end, and selection sort swaps the smallest to the front each pass; both are O(n²), 499,500 comparisons for 1000 numbers, and only bubble sort is stable.
Sorting is one of the things programs do most: a grade list by score, orders by time, search results by relevance. The two simplest sorts are bubble sort and selection sort. Each is five or six lines of code, and each is O(n²): 1000 numbers take 499,500 comparisons, 100,000 numbers about 5 billion. You will not use them at work, but they are where understanding every sort starts: comparing and swapping are a sort's two basic moves, and ideas interviews love, like "stable" and "stopping early", are easiest to see on these two. This lesson writes both and counts every step.
Swapping two values
The most common line in a sort swaps the values in two places. C needs a temporary variable; Python does it in one line:
1a = [5, 1, 4]2a[0], a[1] = a[1], a[0]3print(a)4 5x, y = 1, 26x, y = y, x7print(x, y)
[1, 5, 4] 2 1
a[0], a[1] = a[1], a[0] works out the right-hand side first, packs it into a tuple (1, 5), then unpacks it into the two places on the left in order. So you never "change a[0] first and then read the changed value".
We judge whether a sort is fast by counting, not by timing (timing differs on every run): how many comparisons it made (tests like a[j] > a[j + 1]) and how many swaps. Every piece of code in this lesson carries these two counters.
One line swaps two cells, another changes two variables at once. What does this print?
1a = [5, 1, 4]2a[0], a[2] = a[2], a[0]3x, y = 3, 74x, y = y, x + y5print(a, x, y)
a[2], a[0] is (4, 5), which goes into a[0] and a[2]: [4, 1, 5]. y, x + y uses the old x and y: (7, 3 + 7), so x = 7 and y = 10, not 7 + 7 = 14.Bubble sort
Go from left to right comparing neighbours; when the front one is larger, swap them. After one pass the largest has been swapped all the way to the end, like a bubble rising to the surface. The next pass only needs to sort the first n − 1, the one after that the first n − 2… n − 1 passes in all.
1for i in range(n - 1):2 for j in range(n - 1 - i):3 if a[j] > a[j + 1]:4 a[j], a[j + 1] = a[j + 1], a[j]
1def bubble_sort(a):2 a = a[:] # leave the caller's list alone3 cmps = swaps = 04 n = len(a)5 for i in range(n - 1):6 for j in range(n - 1 - i):7 cmps += 18 if a[j] > a[j + 1]:9 a[j], a[j + 1] = a[j + 1], a[j]10 swaps += 111 return a, cmps, swaps12 13print(bubble_sort([5, 1, 4, 9, 2]))14print(bubble_sort([1, 2, 3, 4, 5]))15print(bubble_sort([5, 4, 3, 2, 1]))16 17data = [(i * 7919) % 10007 for i in range(300)]18result, cmps, swaps = bubble_sort(data)19print(result[:5], cmps, swaps)
([1, 2, 4, 5, 9], 10, 5) ([1, 2, 3, 4, 5], 10, 0) ([1, 2, 3, 4, 5], 10, 10) [0, 19, 48, 96, 125] 44850 22694
The number of comparisons is always (n − 1) + (n − 2) + … + 1 = n(n − 1)/2: 10 for 5 numbers, 44,850 for 300, whatever the input looks like. The number of swaps does depend on the input: 0 for sorted, 10 for reversed (every pair must be swapped). In fact bubble sort's swaps equal exactly the number of inversions: the pairs where the earlier one is larger than the later one. Each swap of neighbours removes exactly one inversion.
Bubble sort 3 6 2 5 1 (smallest first). What does the array look like after pass 1?
Bubble sort swaps two neighbours. Fill in the number so the program sorts 3 6 2 5 1.
1a = [3, 6, 2, 5, 1]2n = len(a)3for i in range(n - 1):4 for j in range(n - 1 - i):5 if a[j] > a[j + 1]:6 a[j], a[j + ] = a[j + 1], a[j]7print(*a)
Stopping early: don't compare what is already sorted
In the bubble sort stage, [1, 2, 3, 4, 5] never swapped but still made 10 comparisons. Yet if the first pass makes no swap at all, every pair of neighbours is in order, so the whole list is already sorted. Add a swapped flag and stop as soon as a pass makes no swap.
1for i in range(n - 1):2 swapped = False3 for j in range(n - 1 - i):4 if a[j] > a[j + 1]:5 a[j], a[j + 1] = a[j + 1], a[j]6 swapped = True7 if not swapped:8 break
1def bubble_sort(a):2 a = a[:]3 cmps = 04 n = len(a)5 for i in range(n - 1):6 swapped = False7 for j in range(n - 1 - i):8 cmps += 19 if a[j] > a[j + 1]:10 a[j], a[j + 1] = a[j + 1], a[j]11 swapped = True12 if not swapped:13 break14 return a, cmps15 16n = 30017sorted_in = list(range(n))18one_off = list(range(n))19one_off[0], one_off[1] = one_off[1], one_off[0] # only the first two are swapped20last_small = list(range(1, n)) + [0] # the smallest is at the end21reversed_in = list(range(n, 0, -1))22 23for name, data in [("sorted", sorted_in), ("first two swapped", one_off), ("smallest last", last_small), ("reversed", reversed_in)]:24 print(name, bubble_sort(data)[1])
sorted 299 first two swapped 597 smallest last 44850 reversed 44850
Sorted input takes only 299 comparisons, which is O(n); with the first two swapped it takes just one more pass. But "smallest last" still takes the full 44,850: each pass of bubble sort can move a small number only one place to the left, so 0 needs 299 passes to get back to the front. Large numbers move right fast (all the way in one pass) and small numbers move left slowly: that is bubble sort's built-in weakness.
Bubble sort with the early exit sorts [2, 1, 3, 4, 5]. What does it print?
1def bubble_sort(a):2 cmps = swaps = 03 n = len(a)4 for i in range(n - 1):5 swapped = False6 for j in range(n - 1 - i):7 cmps += 18 if a[j] > a[j + 1]:9 a[j], a[j + 1] = a[j + 1], a[j]10 swaps += 111 swapped = True12 if not swapped:13 break14 return cmps, swaps15 16print(*bubble_sort([2, 1, 3, 4, 5]))
Which input is slowest for bubble sort with the early stop?
Bubble sort that stops early
✓Complete bubble_sort(a): sort in place, stop when a pass makes no swap, and return the number of comparisons.
[1, 2, 3] 3 [1, 2, 3, 4] 3 [1, 2, 3, 4] 6 [1, 2, 3, 4, 5, 6] 9
1def bubble_sort(a):2 cmps = 03 n = len(a)4 # each pass: swapped = False; set it to True on a swap; break after a pass with no swap5 return cmps6 7for data in [[3, 1, 2], [1, 2, 3, 4], [4, 3, 2, 1], [2, 1, 3, 4, 5, 6]]:8 cmps = bubble_sort(data)9 print(data, cmps)
Selection sort
Another idea: pass 1 finds the smallest of all n and swaps it to index 0; pass 2 finds the smallest of the rest and swaps it to index 1… Each pass swaps just once.
1for i in range(n - 1):2 m = i3 for j in range(i + 1, n):4 if a[j] < a[m]:5 m = j6 a[i], a[m] = a[m], a[i]
1def selection_sort(a):2 a = a[:]3 cmps = swaps = 04 n = len(a)5 for i in range(n - 1):6 m = i7 for j in range(i + 1, n):8 cmps += 19 if a[j] < a[m]:10 m = j11 if m != i:12 a[i], a[m] = a[m], a[i]13 swaps += 114 return a, cmps, swaps15 16print(selection_sort([5, 1, 4, 9, 2]))17print(selection_sort([1, 2, 3, 4, 5]))18print(selection_sort([5, 4, 3, 2, 1]))19 20data = [(i * 7919) % 10007 for i in range(300)]21result, cmps, swaps = selection_sort(data)22print(result[:5], cmps, swaps)
([1, 2, 4, 5, 9], 10, 3) ([1, 2, 3, 4, 5], 10, 0) ([1, 2, 3, 4, 5], 10, 2) [0, 19, 48, 96, 125] 44850 296
On the same 300 numbers, the comparisons are 44,850, as for bubble sort, but the swaps drop from over twenty thousand to under 300: at most one swap per pass, at most n − 1 in all. Selection sort can't stop early: until it has seen all the rest, it doesn't know which is smallest, so sorted input still gets the full count.
Selection sort 5 1 4 9 2. What does the array look like after pass 2?
What do you remember when you find a smaller number? Fill in the blank so selection sort sorts 5 1 4 9 2.
1a = [5, 1, 4, 9, 2]2n = len(a)3for i in range(n - 1):4 m = i5 for j in range(i + 1, n):6 if a[j] < a[m]:7 m = 8 a[i], a[m] = a[m], a[i]9print(*a)
m holds the index of the smallest number so far, so it is j. a[j] would store the number itself, which then goes out of bounds when used as an index; i remembers nothing new.The sort with fewest swaps
✓Complete selection_sort(a): selection sort in place, swapping only when the smallest is not already at position i, and return the number of swaps.
[1, 2, 4, 5, 9] 3 [1, 2, 3] 0 [1, 2, 3] 1 [7] 0
1def selection_sort(a):2 swaps = 03 n = len(a)4 # each pass: m = i, look for something smaller in i + 1 to n - 1; swap only if m != i5 return swaps6 7for data in [[5, 1, 4, 9, 2], [1, 2, 3], [3, 2, 1], [7]]:8 swaps = selection_sort(data)9 print(data, swaps)
Stability: which of two equals comes first
What you sort is often not bare numbers but records: students by score. Two students both have 90, A was before B; after sorting, is A still before B? A sort that keeps equal items in their original order is called stable.
Bubble sort is stable: it swaps only when a[j] > a[j + 1] (strictly greater), so equal items never swap and never pass each other. Selection sort is not stable: when it swaps the smallest to the front, the item that was there gets flung far away, possibly past another item equal to it.
i↑m↑j1def bubble_by_key(a):2 a = a[:]3 for i in range(len(a) - 1):4 for j in range(len(a) - 1 - i):5 if a[j][0] > a[j + 1][0]:6 a[j], a[j + 1] = a[j + 1], a[j]7 return a8 9def selection_by_key(a):10 a = a[:]11 for i in range(len(a) - 1):12 m = i13 for j in range(i + 1, len(a)):14 if a[j][0] < a[m][0]:15 m = j16 a[i], a[m] = a[m], a[i]17 return a18 19records = [(2, "a"), (2, "b"), (1, "c")]20print("bubble: ", bubble_by_key(records))21print("selection:", selection_by_key(records))
bubble: [(1, 'c'), (2, 'a'), (2, 'b')] selection: [(1, 'c'), (2, 'b'), (2, 'a')]
| Bubble sort (with early exit) | Selection sort | |
|---|---|---|
| Comparisons | best n − 1, worst n(n − 1)/2 | always n(n − 1)/2 |
| Swaps | the number of inversions, worst n(n − 1)/2 | at most n − 1 |
| Time | best O(n), average and worst O(n²) | always O(n²) |
| Extra space | O(1) | O(1) |
| Stable | stable | not stable |
In interviews: three things come up: how to improve bubble sort (a swapped flag, O(n) on sorted input); why selection sort is not stable (give an example like 2a 2b 1); which sort swaps least (selection sort, at most n − 1 times). Write >= instead of > and bubble sort stops being stable too, since it swaps equal items.
5a 8 5b 2 has two 5s (a and b only tell them apart). What does selection sort make of it after pass 1?
Each person has a score and a name, bubble-sorted by score from low to high. As written, it swaps people with the same score too. Change only the comparison in the green box so people with the same score keep their original order (A before C, B before D).
1a = [(2, "A"), (1, "B"), (2, "C"), (1, "D")]2n = len(a)3for i in range(n - 1):4 for j in range(n - 1 - i):5 if a[j][0] a[j + 1][0]:6 a[j], a[j + 1] = a[j + 1], a[j]7print(*[f"{s}{name}" for s, name in a])
1B 1D 2A 2C
>= swaps two people even when their scores are equal, so the one in front ends up behind. With >, equal scores are never swapped, and bubble sort is stable.How you write it at work
At work you sort with sorted(a) (returns a new list) or a.sort() (in place, returns None). They are Timsort written in C, O(n log n), and stable: about 8,700 comparisons for 1000 numbers, where bubble sort needs 499,500. To sort records by one field, use key=:
1records = [("Wang", 90), ("Li", 85), ("Zhang", 90), ("Zhao", 70)]2print(sorted(records, key=lambda r: r[1]))3print(sorted(records, key=lambda r: r[1], reverse=True))4 5nums = [5, 1, 4]6print(nums.sort(), nums)
[('Zhao', 70), ('Li', 85), ('Wang', 90), ('Zhang', 90)]
[('Wang', 90), ('Zhang', 90), ('Li', 85), ('Zhao', 70)]
None [1, 4, 5]
Of the two with 90, Wang was before Zhang, and so it stays after sorting; even reverse=True doesn't flip them. That is stability.
- To sort:
sorted/list.sort; don't write bubble or selection sort yourself. a.sort()returns None, soa = a.sort()loses your list.- Selection sort's only strength is few swaps: worth a thought only when a write is very expensive (each swap moves a large block of data, or writes to flash) and comparing is cheap.
sorted and .sort() each sort once. What does this print?
1a = [3, 1, 2]2b = sorted(a)3c = a.sort()4print(a, b, c)
sorted(a) returns a new, sorted list; a.sort() sorts a itself in place and returns None. So a and b are both [1, 2, 3], and c is None. Writing a = a.sort() loses a.Summary
Bubble sort and selection sort
- Bubble: compare neighbours, swap when out of order, the largest goes to the end each pass; swaps = inversions
- With a swapped flag: stop after a pass with no swap; sorted input takes only n − 1 comparisons
- Selection: each pass swaps the smallest to the front; always n(n − 1)/2 comparisons, at most n − 1 swaps
- Bubble is stable (swaps only on >); selection is not (a swap flings an item far away)
- At work use sorted / list.sort: O(n log n), stable, with key and reverse
1a[i], a[j] = a[j], a[i]2if a[j] > a[j + 1]: # bubble: swap only on >, so stable3 a[j], a[j + 1] = a[j + 1], a[j]4if not swapped: break # no swap in a pass: sorted5sorted(records, key=lambda r: r[1])