Sub topic 12
Choosing an Elementary Sort for the Job
This chapter assumes you have read the earlier chapters on bubble sort with early exit, selection sort, and insertion sort, and that you can read Big-O notation. Here the three algorithms are compared on the same inputs. You will see how they differ in measured work and get a short set of rules for picking one.
The main result is that insertion sort is usually the right default. Selection sort wins when writes are expensive. Bubble sort almost never wins on any measure. For large inputs, none of the three is the right choice.
The Properties That Decide the Choice
The earlier chapters each covered one property of these algorithms. The table below puts those properties side by side for an array of n elements.
| Property | Bubble sort (early exit) | Selection sort | Insertion sort |
|---|---|---|---|
| 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, best case | 0 | 0 | 0 |
| Element moves, worst case | n(n − 1)/2 swaps | n − 1 swaps | n(n − 1)/2 shifts |
| Moves in terms of inversions I | I swaps | at most n − 1 swaps, unrelated to I | I shifts |
| Stable | Yes | No (array version) | Yes |
| Adaptive to presorted input | Partly | No | Yes |
| Online (can sort as data arrives) | No | No | Yes |
| Extra space | O(1) | O(1) | O(1) |
Two rows matter most. Bubble sort and insertion sort both move elements exactly I times, where I is the number of inversions. But a bubble sort swap costs two writes and an insertion sort shift costs one. Selection sort ignores the input's order completely. It makes the same n(n − 1)/2 comparisons every time, but it never does more than n − 1 swaps.
Measuring Instead of Guessing
The program below counts comparisons and array writes for each algorithm on four kinds of input. A swap counts as two writes. An insertion shift counts as one write, and placing the key counts as one more write, but only when the key actually moved.
import random
def bubble(a):
a = list(a)
comps = writes = 0
n = len(a)
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]
writes += 2
swapped = True
if not swapped:
break
return a, comps, writes
def selection(a):
a = list(a)
comps = writes = 0
n = len(a)
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]
writes += 2
return a, comps, writes
def insertion(a):
a = list(a)
comps = writes = 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]
writes += 1
j -= 1
if j + 1 != i:
a[j + 1] = key
writes += 1
return a, comps, writes
def nearly_sorted(n, positions):
a = list(range(n))
for p in positions:
a[p], a[p + 1] = a[p + 1], a[p]
return a
n = 200
random.seed(42)
inputs = {
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1)),
"nearly sorted": nearly_sorted(n, [10, 50, 90, 130, 170]),
"random": random.sample(range(n), n),
}
print(f"{'input':<14}{'algorithm':<11}{'comparisons':>12}{'writes':>8}")
for name, data in inputs.items():
for sort in (bubble, selection, insertion):
result, comps, writes = sort(data)
assert result == sorted(data)
print(f"{name:<14}{sort.__name__:<11}{comps:>12}{writes:>8}")The first three inputs are deterministic, so you can check the output against the analysis:
| Input (n = 200) | Algorithm | Comparisons | Writes |
|---|---|---|---|
| sorted | bubble | 199 | 0 |
| sorted | selection | 19900 | 0 |
| sorted | insertion | 199 | 0 |
| reversed | bubble | 19900 | 39800 |
| reversed | selection | 19900 | 200 |
| reversed | insertion | 19900 | 20099 |
| nearly sorted | bubble | 397 | 10 |
| nearly sorted | selection | 19900 | 10 |
| nearly sorted | insertion | 204 | 10 |
The random row depends on the seed. Expect about n(n − 1)/4 ≈ 9950 inversions. Insertion sort will then make roughly 10,000 comparisons and roughly 10,000 writes. Bubble sort will make close to 19,900 comparisons, because early exit rarely triggers on random data, and about twice as many writes as insertion sort. Selection sort will make exactly 19,900 comparisons and at most 398 writes.
The reversed row shows selection sort making only 200 writes. On a reversed array, each swap fixes both ends of the unsorted region, so it needs only n/2 swaps.
Decision Criteria
Input size
All three algorithms are Θ(n²) in the worst case. They are reasonable only when n is small, roughly up to a few dozen elements, or when you know the input is nearly sorted. Past a few hundred random elements, an O(n log n) sort such as merge sort, heapsort, or your language's built-in sort is faster by a wide margin. Python's sorted and list.sort use Timsort, which already uses insertion sort internally on short runs. The next chapter explains that design.
Presortedness
When the input is almost in order, insertion sort runs in Θ(n + I) time. That is close to linear when I is small. Bubble sort with early exit also does well on the nearly sorted input above, but only because each misplaced element was out of place by one position. Bubble sort moves a small element left by just one position per pass. So a single small element at the end of the array, for example [2, 3, 4, ..., n, 1], forces n − 1 passes. Insertion sort handles that same array with one long shift. Selection sort never benefits from presorted input.
Cost of writes
Writes can cost more than comparisons. Examples include flash or EEPROM memory with limited write cycles, large records copied by value, and arrays mirrored to slow storage. In these cases selection sort's bound of n − 1 swaps matters. It does the most comparisons of the three and the fewest writes. If the records are large but you can move them indirectly, another option is to sort an array of indices or pointers with any algorithm and then permute the records once.
Cost of comparisons
If one comparison is expensive, such as comparing long strings, calling a user-supplied key function, or comparing across a network, use binary insertion sort. It cuts comparisons to O(n log n) while staying stable. The number of moves stays Θ(n²) in the worst case, but on contiguous memory those moves are often a cheap block copy.
Stability
If equal keys must keep their original order, for example when you sort by a secondary key and then by a primary key, use insertion sort or bubble sort. Array-based selection sort is unstable because of its long-distance swap. You can make selection sort stable by rotating the minimum into place instead of swapping it, but that turns its O(n) writes into O(n²) writes, which removes its only advantage.
Data arriving over time
Insertion sort is online. Each new element is inserted into a prefix that is already sorted, so the array stays sorted after every arrival. Selection sort and bubble sort need the whole input before their passes mean anything.
A Decision Procedure
Why Bubble Sort Rarely Wins
Bubble sort and insertion sort do the same number of element moves, but each bubble sort swap writes two cells while each insertion shift writes one. Insertion sort also stops each inner loop as soon as it finds the insertion point. Bubble sort keeps scanning to the end of the unsorted region on every pass. Its early exit only helps when no element has to travel far toward the front. In practice insertion sort matches or beats bubble sort on every input, and it is about as short to write.
Bubble sort has two remaining uses. It is easy to explain, and one pass with no swaps is a simple check that an array is sorted, although a plain linear scan does that check just as well.
Common Mistakes When Choosing
- Picking selection sort for speed. Its low swap count looks appealing, but it always makes Θ(n²) comparisons, even on sorted input.
- Assuming early exit makes bubble sort adaptive in general. It helps only when elements are displaced toward the end of the array, not toward the front.
- Ignoring stability until a bug appears. Multi-key sorts quietly give wrong results with an unstable algorithm.
- Hand-writing an elementary sort for large data. The built-in sort is almost always faster and already tested.
Exercise
A firmware routine must sort 32 sensor records stored in EEPROM, where each write wears the memory and is slow. Records with equal readings do not need to keep any particular order. Which elementary sort should you use, and what is the maximum number of record swaps it will make?
Show answer
Selection sort. It makes at most n − 1 = 31 swaps (62 record writes) whatever the input order. Stability does not matter here, so its instability is acceptable.
Exercise
An array of 10,000 elements is in sorted order except that its smallest element was moved to the last position. Compare the work bubble sort with early exit and insertion sort do on it.
Show answer
The smallest element moves left by only one position per bubble sort pass, so bubble sort needs all 9,999 passes and about 50 million comparisons. The array has 9,999 inversions. Insertion sort makes one comparison for each of the first 9,998 insertions and then shifts 9,999 elements for the last one, about 20,000 comparisons and 10,000 shifts in total.
Exercise
You sort a list of employees by department after previously sorting it by name, and you expect names to stay alphabetical within each department. A teammate proposes selection sort because it writes less. What goes wrong, and what should you use?
Show answer
Array-based selection sort is unstable, so its long-distance swaps can reorder employees within a department and break the alphabetical order. Use a stable sort: insertion sort for small lists, or the stable built-in sort (Timsort in Python) for larger ones.
Exercise
Run the measurement program with n = 400. By what factor do selection sort's comparisons on sorted input grow compared with n = 200, and by what factor do insertion sort's comparisons on sorted input grow?
Show answer
Selection sort goes from 19,900 to 79,800 comparisons, about 4 times as many, because it is quadratic. Insertion sort goes from 199 to 399 comparisons, about 2 times as many, because it is linear on sorted input.