Selection sort and insertion sort
🌍 In real life. Two more ways to line up the class.
- Picking the shortest each time. The teacher looks over everyone still waiting, calls the shortest to the front, then looks over the rest and calls the shortest of them to second place, and so on. This is selection sort.
- Sorting playing cards in your hand. You pick up cards one at a time. The cards already in your hand are in order; each new card slides left past every bigger card and drops into its gap. This is insertion sort.
Both keep a sorted part on the left that grows by one value at a time. They differ in what that part promises, and that changes what they cost.
The idea in one sentence: selection sort repeatedly finds the smallest value of the unsorted part and swaps it to that part's front; insertion sort takes the next value and slides it left into its place among the values already sorted.
Their words:
- minimum: the smallest value of a part; selection sort keeps
m, its position so far - sorted part, unsorted part: the left part already handled, and the rest
- key: in insertion sort, the value being placed
- shift: moving a bigger value one place right to open a gap for the key
Selection sort, step by step:
- for each position
ifrom the left: assume the smallest ofa[i:]is atm = i - look at every
jafteri; ifa[j] < a[m], setm = j - swap
a[i]anda[m]: the smallest of the rest is now ati, for good
The blue bar is the smallest seen so far in this pass:
Insertion sort, step by step:
- the first value alone is a sorted part
- take the next value as the key
- while the value to its left is bigger, move the key one place left (in the code below, the bigger value shifts right instead, which is the same move)
- stop at a value that is not bigger, or at the front: the sorted part is one longer
The pale green part is sorted among itself, but not final yet: a small value that comes later can still push it right.
Why they are correct. Each keeps a promise about the left part after every step.
- Selection sort: after pass i, positions 0 to i hold the i + 1 smallest values, in order, for good: each pass brought the smallest of what was left. After n − 1 passes the last value is the biggest, so it is in place too.
- Insertion sort: after placing a[i], positions 0 to i are sorted among themselves. The key stops right after the first value not bigger than it, so everything on its left is not bigger, and everything shifted on its right is bigger. When the last key is placed, the whole list is sorted.
What they cost, by counting.
- Selection sort looks at the whole rest every pass, whatever the order: n − 1 + n − 2 + … + 1 = n(n − 1)/2 comparisons, always O(n²). But it makes at most n − 1 swaps, one per pass, which matters when moving data is expensive.
- Insertion sort moves each key only past the bigger values before it, so its swaps (shifts) equal the inversions, and its comparisons are at most the shifts plus n − 1. A sorted list: n − 1 comparisons, 0 shifts, O(n). A reversed list: n(n − 1)/2, O(n²). A nearly sorted list costs close to O(n), which is why real sorting libraries use insertion sort for small or nearly sorted pieces.
For 1,000 values in reverse order both make 499,500 comparisons; already sorted, selection still makes 499,500 and insertion makes 999.
def selection_sort(a):
for i in range(len(a) - 1):
m = i # where the smallest of a[i:] is
for j in range(i + 1, len(a)):
if a[j] < a[m]:
m = j
a[i], a[m] = a[m], a[i] # bring it to the front of the rest
return a
def insertion_sort(a):
for i in range(1, len(a)):
key = a[i] # the next card to place
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j] # shift a bigger card one place right
j -= 1
a[j + 1] = key # drop the card into the gap
return a
print(selection_sort([5, 2, 8, 1, 4]))
print(insertion_sort([5, 2, 8, 1, 4]))
hand = [2, 5, 9, 11] # cards already in order
hand.append(7) # a new card
print(insertion_sort(hand))Mistakes and edge cases.
- selection: comparing with
a[i]instead ofa[m]: you find the last value smaller thana[i], not the smallest - selection: swapping inside the inner loop: it still sorts, but makes up to n(n − 1)/2 swaps, and loses its one advantage
- insertion:
while j > 0: the key is never compared witha[0], so a value smaller than the first one stays one place too far right - insertion: reading
a[j - 1]whenjis 0:a[-1]is the last value, so Python quietly compares with the wrong one instead of raising an error - forgetting
a[j + 1] = key: the shifts leave a copy of the bigger value in the key's place, and the key is lost
Quiz
The first pass of selection sort. What does this print?
a = [4, 1, 3, 2] m = 0 for j in range(1, len(a)): if a[j] < a[m]: m = j a[0], a[m] = a[m], a[0] print(a, m)What does this insertion sort print?
a = [3, 1, 2] 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 a[j + 1] = key print(a)Moving a value is very slow on some device. Which of these sorts moves values the fewest times on a muddled list?
- Selection sort: at most n − 1 swaps
- Bubble sort
- Insertion sort
A list of 10,000 marks is sorted except that two neighbours are swapped. Which sort finishes with the fewest comparisons?
- Insertion sort: about n comparisons
- Selection sort
- They all make about the same
insertion_sort([3, 1]) gives [3, 1]. Which line is wrong?
def insertion_sort(a): 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 a[j + 1] = key return a
Coding tasks
Write
selection_sort(a): sortain place with selection sort (find the smallest of the rest, swap it to the front of the rest) and return it.Write
insertion_sort(a): sortain place with insertion sort and return it. On a list that is already sorted, each value must stop after one comparison, so 100 sorted values take about 100 comparisons, not thousands.Your hand of cards
handis already in order. Writeinsert_card(hand, card): return a new hand withcardslid into its place, the insertion sort way, without callingsortorsorted. Leavehanditself unchanged.