Insertion Sort
A sorting algorithm that replicates how one orders [see page 11, playing cards].
for j in range(1, len(arr)):
key = arr[j]
i = j - 1
while i >= 0 and arr[i] > key:
arr[i + 1] = arr[i]
i -= 1
arr[i + 1] = key
Code Snippet 1:
Insertion sort implementation. alg:insertion-sort
You can see the insertion sort algorithm in alg:insertion-sort. The main idea behind insertion sort is to compare each element we encounter with all the elements before it and then shuffle it down until we find the first element smaller than it.
The loop invariant for this example is that at the start of each iteration of the
outer for loop the subset of elements from
- Initialisation: At this point
, meaning has only one element therefore its sorted (trivially). - Maintenance: The while loop moves
one position to the right and inserts at the correct position . Then contains the original but in sorted order. - Termination: The for loop ends when
meaning the subset of elements from to , I.E. is in order.