Sub topic 3
Stability, Adaptivity, and Choosing an Elementary Sort
This chapter assumes you can read the bubble, selection, and insertion sort code from the earlier chapters and that you know Big-O notation.
Stability: Which Sorts Keep Equal Keys in Their Original Order
A sort is stable if records with equal keys come out in the same relative order they went in. Bubble sort and insertion sort are stable. Each one moves an element only past a strictly larger neighbor (>), so equal keys never cross each other. Array-based selection sort is unstable. Its long-distance swap can carry one element past another element with the same key:
def selection_sort_by_key(a, key):
n = len(a)
for i in range(n - 1):
m = i
for j in range(i + 1, n):
if key(a[j]) < key(a[m]):
m = j
if m != i:
a[i], a[m] = a[m], a[i]
return a
records = [(2, 'a'), (2, 'b'), (1, 'c')]
print(selection_sort_by_key(records, key=lambda r: r[0]))
# [(1, 'c'), (2, 'b'), (2, 'a')] -- 'a' and 'b' changed orderInversions and Why Nearly Sorted Input Favors Insertion Sort
An inversion is a pair of positions i < j where a[i] > a[j]. Each adjacent swap in bubble sort and each shift in insertion sort removes exactly one inversion. Insertion sort therefore runs in O(n + I) time, where I is the number of inversions. Nearly sorted input has few inversions, so insertion sort runs close to linear time on it.
def count_inversions(a):
n = len(a)
return sum(1 for i in range(n) for j in range(i + 1, n) if a[i] > a[j])
def insertion_sort_shifts(a):
a = list(a)
shifts = 0
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
shifts += 1
a[j + 1] = key
return shifts
data = [3, 1, 4, 1, 5, 9, 2, 6]
print(count_inversions(data), insertion_sort_shifts(data)) # 8 8Binary Insertion Sort: Fewer Comparisons, Same Number of Moves
Binary insertion sort uses binary search to find each insertion point. This cuts comparisons to O(n log n). The number of element moves does not change, so the worst case is still O(n²). The bisect_right call places a key after any equal keys, which keeps the sort stable.
import bisect
def binary_insertion_sort(a):
for i in range(1, len(a)):
key = a[i]
pos = bisect.bisect_right(a, key, 0, i)
a[pos + 1:i + 1] = a[pos:i]
a[pos] = key
return a
print(binary_insertion_sort([4, 2, 7, 1, 3, 2])) # [1, 2, 2, 3, 4, 7]Use it when comparisons cost much more than moves, for example when comparing long strings.
Choosing an Elementary Sort for the Job
| Situation | Choose | Reason |
|---|---|---|
| Writes are expensive | Selection sort | At most n − 1 swaps |
| Input is nearly sorted | Insertion sort | O(n + I) time |
| Stability is required | Insertion sort | Stable and adaptive |
| Teaching or a quick sortedness check | Bubble sort with early exit | Simple, O(n) on sorted input |
Where Insertion Sort Survives: Small Runs in Hybrid Sorts
Hybrid sorts use insertion sort on small subarrays. Timsort extends short runs with binary insertion sort up to a minimum run length of about 32 to 64 elements. Introsort switches to insertion sort below roughly 16 elements. At those sizes, insertion sort's low overhead and cache-friendly sequential access beat the constant factors of O(n log n) algorithms.
Exercise
A list of 10,000 orders is already sorted by date. Then 5 new orders are appended at the end with random dates. You must sort by date and keep ties in their original order. Which elementary sort fits, and roughly how much work does it do?
Show answer
Insertion sort. It is stable, and the input has at most about 5 × 10,000 = 50,000 inversions. It runs in O(n + I), roughly 60,000 steps, compared with about 50 million comparisons for selection sort.