Sub topic 2
Selection Sort and Insertion Sort, Proved and Compared
This chapter assumes you can read Python loops, index into lists, and use Big-O notation. It also assumes you know the bubble sort and the cost model from the previous chapter.
Selection Sort: Repeatedly Picking the Minimum
Selection sort scans the unsorted part of the list for its smallest value. It then swaps that value into the first unsorted position.
def selection_sort(a):
n = len(a)
for i in range(n - 1):
# a[:i] is sorted and holds the i smallest values.
m = i
for j in range(i + 1, n):
if a[j] < a[m]:
m = j
if m != i:
a[i], a[m] = a[m], a[i]
return a
print(selection_sort([64, 25, 12, 22, 11])) # [11, 12, 22, 25, 64]Selection sort makes n(n-1)/2 comparisons on every input, but at most n-1 swaps. That makes it a reasonable choice when writes cost much more than reads.
Insertion Sort: Growing a Sorted Prefix One Element at a Time
Insertion sort takes the next element, called the key, and shifts the larger sorted elements one place to the right. It then drops the key into the gap.
def insertion_sort(a):
for i in range(1, len(a)):
# a[:i] is sorted; insert a[i] into it.
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j] # shift right instead of swapping
j -= 1
a[j + 1] = key
return a
print(insertion_sort([12, 11, 13, 5, 6])) # [5, 6, 11, 12, 13]Proving Each Sort Correct with Loop Invariants
A loop invariant is a statement that holds before every iteration of a loop. When the loop ends, the invariant gives you the result you want to prove.
- Selection sort:
a[:i]is sorted and holds the i smallest values. When i = n-1, the last element must be the largest, so the whole list is sorted. - Insertion sort:
a[:i]holds the original first i elements in sorted order. When i = n, the whole list is sorted. - Bubble sort: the last i positions hold their final values.
Best, Average, and Worst Cases Side by Side
The bubble sort row assumes the early-exit version from the previous chapter.
| Algorithm | Best comparisons | Worst comparisons | Worst swaps or shifts | Average time |
|---|---|---|---|---|
| Bubble (early exit) | n-1 | n(n-1)/2 | n(n-1)/2 swaps | O(n²) |
| Selection | n(n-1)/2 | n(n-1)/2 | n-1 swaps | O(n²) |
| Insertion | n-1 | n(n-1)/2 | n(n-1)/2 shifts | O(n²), about n²/4 shifts |
Bubble sort and insertion sort reach their best case on sorted input. Selection sort gets no benefit from sorted input because it always scans the whole unsorted part.
Exercise
How many comparisons do selection sort and insertion sort each make on an already sorted list of 10 elements?
Show answer
Selection sort makes 10·9/2 = 45 comparisons. Insertion sort makes 9, one per key, because each key is already larger than its left neighbor.