Insertion Sort: Shifting, Gaps and Cost
Grow a sorted prefix one value at a time: lift the next value out, shift every larger value one slot right, and drop the value into the gap.
How It Works
- Start at i = 1: a single value,
a[0], is already a sorted prefix - Copy
a[i]intokey; its slot is now a gap - While the value left of the gap is greater than
key, move it one slot right; the gap moves left - Stop at a value ≤
keyor at the start of the array, and writekeyinto the gap - Increase i and repeat until the whole array is the sorted prefix
Insertion sort keeps the left part of the array sorted and grows it by one value per round. It is how most people sort a hand of cards: take the next card, slide it left past every larger card, and drop it in.
On [2, 5, 9, 3, 8] the first two rounds do nothing: 5 and 9 are already larger than everything on their left, so each costs one comparison. Round three lifts 3, shifts 9 and then 5 one place right, stops at 2, and drops 3 into slot 1. Round four lifts 8, shifts 9, stops at 5, and the array is [2, 3, 5, 8, 9].
The insertion sort algorithm only ever moves values right by one slot, and only past values that are strictly greater. Everything else about it, its cost, its stability and its best case, follows from those two facts.
- The sorted prefix is sorted among itself, but a later value can still land in the middle of it
- Empty and one-element arrays skip the loop entirely
Shifting, Not Swapping
A first attempt often swaps the key left one place at a time. Each swap is three writes (through a temporary), so moving the key k places costs 3k writes.
Shifting does better. The key is saved once, each larger value is copied one slot right (one write each), and the key is written once at the end: k + 1 writes for the same k places. In the trace above, moving 3 two places costs 3 writes instead of 6.
Saving the key first is not optional. Shifting 9 into the key's slot overwrites the key, so code that reads a[i] again after the first shift has lost it.
- The gap moves left; the key is written exactly once per round
- The inner loop reads memory backwards and contiguously, which suits CPU caches
Insertion Sort Time Complexity
Each shift moves one value past one smaller value that was behind it, so it fixes exactly one inversion, a pair that is out of order. The number of shifts therefore equals the number of inversions d, and the running time is O(n + d).
- Time complexity: best O(n), average O(n²), worst O(n²)
- Space complexity: O(1), sorted in place
That one formula gives every case. Sorted input has d = 0: each round makes one comparison and stops, n − 1 comparisons in all. Reversed input has every pair inverted, d = n(n − 1)/2, so for n = 1,000 that is 499,500 shifts. Random input has about n²/4 inversions on average, still quadratic.
Insertion sort is adaptive: nearly sorted input, where each value is only a few places from home, runs in close to linear time. That is why library sorts hand it the small pieces. C++'s std::sort (introsort) stops recursing on ranges of 16 or fewer and finishes them with insertion sort, and Timsort, used by Python and by Java for objects, extends short runs to a minimum length with binary insertion sort before merging them.
| Input | Comparisons | Shifts |
|---|---|---|
| Sorted | n − 1 | 0 |
| d inversions | between d and n − 1 + d | d |
| Random | about n²/4 | about n²/4 |
| Reversed | n(n − 1)/2 | n(n − 1)/2 |
- Binary insertion sort finds the slot with binary search, cutting comparisons to O(n log n), but the shifts stay O(n²)
- Insertion sort is online: it can sort values as they arrive, since each round only needs the values seen so far
Terms, operations, and practical uses
Core mechanics
- Sorted prefixThe invariant: elements before the current index are always in order relative to each other.
- ShiftingMoving larger elements one place right to open a gap — one write each, versus three for a swap.
- Binary insertionUsing binary search to find the position; it cuts comparisons but not the shifts.
Properties
- StableShifting stops at the first element not greater than the key, so equal values keep their order.
- AdaptiveCost tracks inversions, so nearly sorted input approaches O(n).
- OnlineEach round needs only the values already seen, so it can sort a stream as values arrive.
Where it is used
- Small subarraysIntrosort stops recursing on ranges of about 16 and finishes them with insertion sort, where its low overhead wins.
- TimsortUses binary insertion sort to extend short runs before merging them.
- Shell sortRuns insertion sort over gapped subsequences, so the final gap-1 pass has few inversions left.
Code in Python, C++ and Java
def insertion_sort(values):
for i in range(1, len(values)):
key = values[i] # lift the value out, leaving a gap
j = i - 1
# shift every larger value one slot right
while j >= 0 and values[j] > key:
values[j + 1] = values[j]
j -= 1
values[j + 1] = key # drop the key into the gap
return values
print(insertion_sort([2, 5, 9, 3, 8]))#include <iostream>
#include <vector>
void insertionSort(std::vector<int>& values) {
for (std::size_t i = 1; i < values.size(); ++i) {
const int key = values[i]; // lift the value out, leaving a gap
int j = static_cast<int>(i) - 1;
// shift every larger value one slot right
while (j >= 0 && values[j] > key) {
values[j + 1] = values[j];
--j;
}
values[j + 1] = key; // drop the key into the gap
}
}
int main() {
std::vector<int> values{2, 5, 9, 3, 8};
insertionSort(values);
std::cout << '[';
for (std::size_t i = 0; i < values.size(); ++i) std::cout << (i ? ", " : "") << values[i];
std::cout << "]\n";
}import java.util.Arrays;
public class Main {
static void insertionSort(int[] values) {
for (int i = 1; i < values.length; i++) {
int key = values[i]; // lift the value out, leaving a gap
int j = i - 1;
// shift every larger value one slot right
while (j >= 0 && values[j] > key) {
values[j + 1] = values[j];
j--;
}
values[j + 1] = key; // drop the key into the gap
}
}
public static void main(String[] args) {
int[] values = {2, 5, 9, 3, 8};
insertionSort(values);
System.out.println(Arrays.toString(values));
}
}Step through it
Running on [2, 5, 9, 3, 8]
Stability and Edge Cases
Insertion sort is stable: equal values keep their original order. The inner loop shifts only while a[j] > key, so it stops at an equal value and the key lands after it.
Change the test to >= and the key slides past equal values, reversing their order. The output is still sorted by value, so the bug goes unnoticed until records with equal keys come out in the wrong order, for example after sorting by name and then by date.
Two loop details catch people out. The bounds check j >= 0 must come first in the condition, or a[-1] is read when the key is the smallest value so far (in Python that silently reads the last element). And the key is written at j + 1, one past where the scan stopped.
- Duplicates cost nothing extra: the scan stops at the first equal value
- On a linked list the same idea relinks nodes instead of shifting; see insertion sort list
Insertion Sort vs Selection Sort
Both are simple O(n²) sorts that grow a sorted prefix, but the prefix means different things. Selection sort puts the smallest remaining value at the end of its prefix, so each value it places is final. Insertion sort's prefix holds the first i values in sorted order, and a later value can still be inserted in the middle.
In practice insertion sort is usually the better choice: it is adaptive and stable, while selection sort always makes n(n − 1)/2 comparisons and is not stable. Selection sort wins only where writes are very expensive, since it makes at most n − 1 swaps. Against bubble sort, insertion sort does the same number of moves (one per inversion) with fewer comparisons and fewer writes.
| Insertion sort | Selection sort | |
|---|---|---|
| Sorted input | n − 1 comparisons | n(n − 1)/2 comparisons |
| Writes | one per inversion, plus one per round | at most n − 1 swaps |
| Stable | yes | no (the usual array version) |
| Prefix after round i | first i + 1 values, sorted | the i + 1 smallest, final |
- Shell sort runs insertion sort over spaced-out elements first, so the final plain pass has few inversions left
- For large inputs use an O(n log n) sort: merge sort or quick sort