Insertion sort
easy 14 minInsertion sort builds a sorted prefix one value at a time: it takes the next value, shifts every bigger value in the prefix one slot right, and drops the value into the gap.
Video lesson · Chapter 1 of 6
Find the gap for seven
Insertion sort — One record out of order
1:25Reel
Read caption
DJ Inez inserts record 3 into a sorted sleeve rack holding 2, 5, and 7. Hold the key. Slide bigger items. Fill the gap.
How it works
Step through the idea, or press Play.
Pick the key. Take the first value of the unsorted part; everything to its left is already sorted
Understand it
Start here
What insertion sort is
Insertion sort works the way most people sort playing cards in their hand. You start with one card, which is trivially sorted. You pick up the next card and slide it into the right place among the cards you already hold. You repeat, one card at a time, until the whole hand is sorted.
Pick key
Take the next unsorted value as the key to insert.
Shift right
Slide every bigger value in the sorted part one slot right to make room.
Insert
Write the key into the gap. The sorted part is now one longer.
The picture
A sorted part that grows by one
At any moment the array has two parts: a sorted prefix on the left and an unsorted suffix on the right. Each pass moves the boundary one slot right. Here is [5, 2, 4, 1, 3], with the key of each pass in bold:
| Pass | Key | What moves | Array after the pass |
|---|---|---|---|
| start | nothing, [5] is sorted on its own | 5 | 2, 4, 1, 3 | |
| 1 | 2 | : shift 5 right | 2, 5 | 4, 1, 3 |
| 2 | 4 | : shift 5 right; stop | 2, 4, 5 | 1, 3 |
| 3 | 1 | 1 is smallest: shift 5, 4 and 2 right | 1, 2, 4, 5 | 3 |
| 4 | 3 | shift 5 and 4; stop, insert between 2 and 4 | 1, 2, 3, 4, 5 |
- 1ScanSelect the next unsorted value
- 2CompareAgainst the sorted part, right to left
- 3InsertInto the gap left by the shifts
- 4ProgressMove the boundary and repeat
Scan, Compare, Insert, Progress: one loop per value after the first.
The algorithm
The inner loop
One pass: insert arr[i] into arr[0..i-1]
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 right j -= 1 arr[j + 1] = key # insert into the gap return arrprint(insertion_sort([64, 34, 25, 12, 22, 11, 90]))# [11, 12, 22, 25, 34, 64, 90]Worked example
Sorting [5, 2, 9, 1, 5]
- 1
Start: [5] is sorted
Sorted part
[5], unsorted part[2, 9, 1, 5]. - 2
Key 2
, so shift 5 right and insert 2. Sorted
[2, 5], unsorted[9, 1, 5]. - 3
Key 9
on the first comparison: no shift. The best case for one key. Sorted
[2, 5, 9]. - 4
Key 1
, , : shift all three and insert 1 at the front. The worst case for one key. Sorted
[1, 2, 5, 9]. - 5
Key 5
, shift 9. Then , stop, and insert after the existing 5. Result
[1, 2, 5, 5, 9].
| Key | Comparisons | Shifts |
|---|---|---|
| 2 | 1 | 1 |
| 9 | 1 | 0 |
| 1 | 3 | 3 |
| 5 | 2 | 1 |
| total | 7 | 5 |
Correctness
The loop invariant
Why does this always work? At the start of every pass , the slice arr[0..i-1] holds exactly the values that were originally in those slots, in sorted order. That statement is the loop invariant.
Invariant before pass i
Initialise, maintain, terminate
Complexity
Best case: O(n)
On already sorted input every key is bigger than the value just before it. The test arr[j] > key fails immediately, so each pass costs one comparison and zero shifts.
Sorted input
Complexity
Worst case: n(n-1)/2 shifts
On reversed input every key is the smallest so far, so pass shifts all values in front of it. Adding the passes is an arithmetic series.
Reversed input
| n | Best: comparisons | Average: about | Worst: |
|---|---|---|---|
| 10 | 9 | about 23 | 45 |
| 20 | 19 | about 95 | 190 |
| 100 | 99 | about 2,475 | 4,950 |
| 1,000 | 999 | about 249,750 | 499,500 |
key and j.The math
Inversions: the exact cost
An inversion is a pair of positions with : two values in the wrong order. Each shift moves one bigger value past the key, which fixes exactly one inversion and creates none. So the number of shifts is not just bounded by the inversions; it equals them.
Cost in terms of inversions
Range and average
Head to head
Insertion vs bubble vs selection
| Property | Insertion sort | Selection sort | Bubble sort |
|---|---|---|---|
| Best time | with an early-exit flag | ||
| Worst time | |||
| Space | |||
| Stable | Yes | No | Yes |
| Adaptive | Yes | No | Only with the flag |
| Writes | one per inversion | at most swaps | one swap per inversion |
| Best use | Small or nearly sorted data | When writes are expensive | Teaching |
Which simple sort?
Variants
Binary insertion, Shell sort and linked lists
Binary insertion sort
Find the spot with binary search: comparisons per key, total. Shifts are still , so the time stays quadratic.
Shell sort
Insertion sort on elements a gap apart, with gaps shrinking to 1. Far-apart values move early, so the final pass is nearly sorted and cheap.
Linked list
No shifting: unlink the node and splice it in. Still comparisons, because finding the spot is a linear walk.
Hybrid sorts
Timsort (Python, Java objects) and introsort (C++) switch to insertion sort for small runs, often around 16 to 64 values.
import bisectdef binary_insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] pos = bisect.bisect_right(arr, key, 0, i) # bisect_right keeps it stable arr[pos + 1:i + 1] = arr[pos:i] # shift the block right arr[pos] = key return arrprint(binary_insertion_sort([5, 2, 9, 1, 5])) # [1, 2, 5, 5, 9]Pattern spotting
When to reach for it
Good for
- Small arrays, roughly under 50 values.
- Nearly sorted data: when only a few values are out of place.
- Online sorting: values arrive one at a time and the list must stay sorted.
- When a stable, in-place, simple sort is needed.
- Finishing off small pieces inside merge sort or quick sort.
Avoid when
- The array is large and random: use an sort.
- The input is reversed or close to it: the worst case.
- Performance on big inputs is critical.
- Writes are very expensive (flash memory): selection sort writes less.
How a hybrid sort uses insertion sort
Almost sorted
A log file with a few late entries, or a list after one new value was appended.
Arriving one by one
Keep a leaderboard or a hand of cards sorted after every insert.
Tiny inputs
Sorting 5 to 20 items where simplicity matters more than asymptotics.
Recap
Key takeaways
Key points
- Insertion sort grows a sorted prefix: take the key, shift bigger values right, write the key into the gap.
- Best case on sorted input ( comparisons, 0 shifts); worst case shifts on reversed input; average .
- Shifts equal the number of inversions, so the running time is .
- Stable (use
>not>=), in place ( space), adaptive and online. - Beats bubble sort in practice; selection sort writes less but is not stable or adaptive.
- Real libraries use it for small runs inside Timsort and introsort.