Insertion Sort
Insertion sort is a comparison-based sorting algorithm that grows a sorted prefix one element at a time: each pass lifts the next value out of the array, shifts every larger element in the prefix one slot right, and drops the value into its correct place. It is stable, in-place, O(n²) worst case, and O(n) when the input is already sorted.
It works the same way as sorting a hand of playing cards: pick up one card at a time, shift larger cards in your hand rightward, and place the new card where it fits.
How Insertion Sort Works
Insertion sort uses one outer loop and one backward inner loop. The outer loop runs i from 1 to n − 1: positions 0..i − 1 form the sorted prefix, and arr[i] is the next value to insert. Saving key = arr[i] leaves slot i free to be overwritten.
The inner loop scans j from i − 1 down toward 0. While arr[j] > key, it shifts arr[j] one slot right (arr[j + 1] = arr[j]) and decrements j. Once it reaches a value less than or equal to key, or moves past index 0 to j = −1, the loop stops and writes key into arr[j + 1].
The loop invariant is that arr[0..i − 1] is sorted at the start of each outer pass. Every pass inserts arr[i] into that sorted prefix, so when i reaches n, the entire array is sorted.
Insertion Sort Step by Step
The default input is [38, 12, 56, 7, 41, 23, 19].
Pass 1 (i = 1): lift key = 12 against the sorted prefix [38]. Because 38 > 12, 38 shifts right and j decrements to −1, placing 12 at index 0: [12, 38, 56, 7, 41, 23, 19].
Pass 2 (i = 2): lift key = 56. Its neighbor 38 is smaller than 56, so the inner loop exits immediately without shifting, and 56 returns to index 2. One comparison and zero shifts is the fast path that gives insertion sort linear behavior on sorted input.
Pass 3 (i = 3): lift key = 7. Every element in the prefix is larger, so 56, 38, and 12 each shift right in turn, j reaches −1, and 7 lands at index 0: [7, 12, 38, 56, 41, 23, 19].
The remaining passes follow the same rule. Pass 4 shifts 56 and places 41 to produce [7, 12, 38, 41, 56, 23, 19]. Pass 5 shifts 56, 41, and 38 to place 23 at index 2, giving [7, 12, 23, 38, 41, 56, 19]. Pass 6 shifts 56, 41, 38, and 23 to place 19 at index 2, finishing with [7, 12, 19, 23, 38, 41, 56].
In the animation, the cell at i lifts above the row as the key while j scans left. Each shifted element slides rightward into the open slot, and the key drops into j + 1 once the scan stops.
Time and Space Complexity
| Case | Time |
|---|---|
| Best (already sorted) | O(n) |
| Average | O(n²) |
| Worst (reverse sorted) | O(n²) |
Extra space is O(1) because the sort runs in place. The animated version uses the shift-based form (one saved key and repeated arr[j + 1] = arr[j] assignments) rather than the swap-based variant.
The O(n) best case comes from the inner loop guard, while j >= 0 and arr[j] > key, which fails on the first value comparison of each pass when the input is sorted. More generally, each inversion causes one shift, so the running time is Θ(n + I), where I is the number of inversions. A low inversion count keeps the cost small, and O(n) requires I = O(n) ("nearly sorted" alone does not give a precise bound). That adaptivity makes insertion sort practical for short runs with little disorder.
Edge Cases
- Empty or one-element array: the outer loop runs zero times.
- Already sorted input: every inner loop exits on its first comparison, giving
n − 1comparisons total and O(n) time. - All equal values:
arr[j] > keyis never true, so zero shifts occur, also taking O(n) time. - Duplicates: insertion sort is stable because the strict
>guard stops at an equal value instead of shifting past it, preserving the original order of equal elements.
Common Mistakes
- Using
>=instead of>in the guard. The array still finishes sorted, but equal values shift past each other and stability is lost. - Placing the key at
arr[j]instead ofarr[j + 1]. After the loop exits,arr[j]is the element that stopped the scan (orjis −1), so the open slot sits atj + 1. - Overwriting before saving the key. Skipping
key = arr[i]causes the first shift to overwrite the value being inserted. - Shifting in the wrong direction. The loop body is
arr[j + 1] = arr[j], moving values right to open the gap. Writingarr[j] = arr[j - 1]copies in the opposite direction and shifts the gap away from the insertion slot.
Keep exploring
A few lessons that share the same technique or lead into the next idea.
Embed this lesson in a blog, docs, or course?
Found a mistake or something unclear?