Sub topic 12
Choosing an Elementary Sort for the Job
This chapter assumes you have already seen how bubble, selection, and insertion sort work. It also assumes you know their best, average, and worst-case costs, which sorts are stable, and how inversions relate to the work insertion sort does. Here those facts are combined into a way to choose between the three.
The Three Sorts on One Page
The table lists the properties that matter when you pick a sort. Here n is the input length and I is the number of inversions, the pairs of elements that are out of order.
| Property | Bubble (early exit) | Selection | Insertion |
|---|---|---|---|
| Comparisons, best case | n − 1 | n(n − 1)/2 | n − 1 |
| Comparisons, worst case | n(n − 1)/2 | n(n − 1)/2 | n(n − 1)/2 |
| Element moves | I swaps | at most n − 1 swaps | I shifts |
| Stable | Yes | No (array version) | Yes |
| Adaptive to presorted input | Yes, weakly | No | Yes |
| Extra space | O(1) | O(1) | O(1) |
A swap writes two array slots. A shift writes one. Bubble sort and insertion sort both do work proportional to I, so each moves an out-of-order element one position at a time. Insertion sort does it with half the writes and usually fewer comparisons. That is why bubble sort rarely wins a practical comparison.
Measuring Instead of Guessing
The script below counts comparisons and moves (swaps or shifts) for each sort on sorted and reversed input of length 8.
def bubble_counts(a):
a = list(a)
n = len(a)
comps = swaps = 0
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
comps += 1
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swaps += 1
swapped = True
if not swapped:
break
return comps, swaps
def selection_counts(a):
a = list(a)
n = len(a)
comps = swaps = 0
for i in range(n - 1):
m = i
for j in range(i + 1, n):
comps += 1
if a[j] < a[m]:
m = j
if m != i:
a[i], a[m] = a[m], a[i]
swaps += 1
return comps, swaps
def insertion_counts(a):
a = list(a)
comps = shifts = 0
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0:
comps += 1
if a[j] <= key:
break
a[j + 1] = a[j]
shifts += 1
j -= 1
a[j + 1] = key
return comps, shifts
for label, data in [("sorted", list(range(8))), ("reversed", list(range(8, 0, -1)))]:
print(label, bubble_counts(data), selection_counts(data), insertion_counts(data))
# sorted (7, 0) (28, 0) (7, 0)
# reversed (28, 28) (28, 4) (28, 28)Each pair is (comparisons, moves). Selection sort makes 28 comparisons no matter what the input looks like, but it needs only 4 swaps to reverse a reversed array. Insertion sort finishes sorted input in 7 comparisons and no moves.
Decision Criteria
- Write cost dominates. Selection sort bounds the number of swaps at n − 1. This helps when each write is slow or wears out the hardware, as with flash or EEPROM cells, or when each element is a large record that is expensive to copy.
- Input is nearly sorted. Insertion sort runs in O(n + I) time. If only a few elements are out of place, it is close to linear.
- Stability is required. Use insertion sort. Selection sort's long-distance swaps can reorder equal keys.
- Small n. For roughly 10 to 50 elements, insertion sort's tight inner loop and lack of overhead often beat O(n log n) algorithms. This is the next chapter's topic.
- Large n with random order. None of the three is a good choice. All are Θ(n²) on average. Use the library sort.
Exercises
Exercise
A device stores 200 sensor readings in flash memory, where each write is about 1,000 times slower than a read. The order of equal readings does not matter. Which elementary sort should you choose, and why?
Show answer
Selection sort. It performs at most n − 1 = 199 swaps (398 writes) regardless of input. Insertion and bubble sort can perform up to n(n − 1)/2 = 19,900 moves in the worst case. Its lack of stability does not matter here.
Exercise
A list of 10,000 orders is sorted by timestamp, and then 5 new orders are appended at the end. The sort must keep orders with equal timestamps in their existing order. Which sort fits best, and roughly how much work does it do?
Show answer
Insertion sort. It is stable, and its cost is O(n + I). Each appended order can create at most 10,004 inversions, so I is at most about 50,000. That gives roughly 60,000 steps instead of the about 50 million that a quadratic worst case would need.