Insertion Sort
Insertion sort works the way many people sort a hand of playing cards. The left part of the array is kept sorted. Each new value is taken from the right part and moved left until it sits after the first smaller (or equal) value, like sliding a card into place.
How it works
- A single value is a sorted prefix, so start with
a[0]alone. - Take
a[1]. While the value to its left is larger, move it one step left. - Now
a[0..1]is sorted. Takea[2]and do the same, and so on until the end.
Implementation
The classic version doesn't swap at every step. It lifts the value out (key), shifts the larger values one slot to the right, and drops the key into the gap. This does the same thing as the swaps in the animation with fewer writes.
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j] # shift the larger value right
j -= 1
arr[j + 1] = key
print(f"Insert {key}: {arr[:i + 1]} | {arr[i + 1:]}")
return arr
print(insertion_sort([8, 3, 5, 1, 9, 2]))Insert 3: [3, 8] | [5, 1, 9, 2]
Insert 5: [3, 5, 8] | [1, 9, 2]
Insert 1: [1, 3, 5, 8] | [9, 2]
Insert 9: [1, 3, 5, 8, 9] | [2]
Insert 2: [1, 2, 3, 5, 8, 9] | []
[1, 2, 3, 5, 8, 9]
The | separates the sorted prefix from the values not yet processed. Each line matches a "Prefix 0..i is sorted" frame of the animation.
Best case and worst case
Insertion sort's work depends heavily on the input. On a sorted array the while loop stops immediately for every value: only n - 1 comparisons. On a reversed array every value must travel all the way to the front.
def insertion_sort_count(arr):
comparisons = shifts = 0
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0:
comparisons += 1
if arr[j] <= key:
break
arr[j + 1] = arr[j]
shifts += 1
j -= 1
arr[j + 1] = key
return comparisons, shifts
cases = {
"sorted": [1, 2, 3, 4, 5, 6, 7, 8],
"nearly sorted": [1, 2, 4, 3, 5, 6, 8, 7],
"reversed": [8, 7, 6, 5, 4, 3, 2, 1],
}
for name, data in cases.items():
comps, shifts = insertion_sort_count(list(data))
print(f"{name:>13}: {comps:>2} comparisons, {shifts:>2} shifts") sorted: 7 comparisons, 0 shifts
nearly sorted: 9 comparisons, 2 shifts
reversed: 28 comparisons, 28 shifts
The number of shifts equals the number of inversions in the input: pairs of values that are in the wrong order. Nearly sorted data has few inversions, so insertion sort is very fast on it. That is why real-world sorts such as Python's Timsort use insertion sort for short runs.
Inserting into an already sorted list
The inner loop is useful on its own: if you receive values one at a time and want to keep a list sorted, insert each new value into place. The standard library's bisect.insort does this (it finds the position with binary search, then inserts):
import bisect
leaderboard = []
for score in [420, 380, 510, 380, 470]:
bisect.insort(leaderboard, score)
print(leaderboard)[420]
[380, 420]
[380, 420, 510]
[380, 380, 420, 510]
[380, 380, 420, 470, 510]
Properties
| Property | Insertion sort |
|---|---|
| Time, worst and average | O(n²) |
| Time, best (sorted input) | O(n) |
| Extra memory | O(1), in place |
| Stable? | Yes: a value never moves past an equal one (arr[j] > key) |
| Online? | Yes: it can sort values as they arrive |
Note: Changing
arr[j] > keytoarr[j] >= keystill sorts, but equal values jump over each other and the sort is no longer stable.
Test yourself
During insertion sort, what is true about the part of the array to the left of the current value?
- It contains the smallest values of the whole array
- It is sorted
- It is unchanged from the input
- It is empty
How many comparisons does insertion sort make on an already sorted array of 8 values?
- 0
- 7
- 28
- 64
On which input is insertion sort fastest?
- Reversed data
- Data with many inversions
- Nearly sorted data
- It is always equally fast