Free explainer · Video · Code · Quiz
Insertion Sort
Grow a sorted prefix one value at a time, like sorting a hand of cards: take the next value, shift the bigger ones right, drop it into the gap. A stable, in-place sort that is O(n) on nearly sorted input and O(n²) in the worst case, and the small-run workhorse inside TimSort and introsort.
- Difficulty
- Easy
- Time
- O(n²) worst, O(n) best
- Space
- O(1)
Try it yourself
Step through it at your own pace — this is Insertion Sort Animation, running right on the page.
LiveInsertion Sort Animation
Loading the preview…
How it works
The idea, a worked example, and the traps to avoid.
The idea
Think of sorting a hand of playing cards. You pick up the cards one at a time with your right hand. The cards already in your left hand are in order, so for each new card you slide your eyes along the hand from the right, push the bigger cards one slot over to make room, and tuck the new card into the gap. When the last card is tucked in, the whole hand is sorted.
That's insertion sort. The array is split in two: a sorted prefix on the left and the untouched rest on the right. Each step takes the first untouched value, the key, and inserts it into the prefix, so the prefix grows by one.
The listing does it in three moves per key:
- Take the key.
key = values[i], and remember thatvalues[0..i)is already sorted. - Shift. Walk
jleft fromi - 1whilevalues[j] > key, copying each bigger value one place right (values[j + 1] = values[j]). - Drop. The walk stopped at a value that is not bigger, or at the front of the array. The gap is at
j + 1, sovalues[j + 1] = key.
The while loop does two checks, j >= 0 first so that we never read before the front of the array, then values[j] > key.
Walkthrough
Sort [5, 2, 8, 1, 7, 3, 6, 4]. The first value is a sorted prefix of one, so the loop starts at i = 1. "Compares" counts each time a prefix value is checked against the key.
| Key | Compares | Shifts | Array after inserting (bar = end of the sorted prefix) |
|---|---|---|---|
| 2 | 1 | 1 | [2, 5 │ 8, 1, 7, 3, 6, 4] |
| 8 | 1 | 0 | [2, 5, 8 │ 1, 7, 3, 6, 4] |
| 1 | 3 | 3 | [1, 2, 5, 8 │ 7, 3, 6, 4] |
| 7 | 2 | 1 | [1, 2, 5, 7, 8 │ 3, 6, 4] |
| 3 | 4 | 3 | [1, 2, 3, 5, 7, 8 │ 6, 4] |
| 6 | 3 | 2 | [1, 2, 3, 5, 6, 7, 8 │ 4] |
| 4 | 5 | 4 | [1, 2, 3, 4, 5, 6, 7, 8] |
Watch the key 1: it is compared with 8, 5 and 2, all bigger, so all three shift right, and then j falls off the front (j = -1) and the 1 lands at index 0. The key 8 is the opposite: its neighbour 5 is not bigger, so nothing moves and the 8 is written back where it was. In total that's 19 comparisons and 14 shifts.
The shift count is no accident. Every shift moves one value past the key, which fixes exactly one inversion (a pair that is out of order). This array has 14 inversions, and insertion sort makes exactly 14 shifts, no more and no fewer.
Why it's correct
The invariant: at the start of each pass, values[0..i) holds the first i values of the original array, in sorted order. Not the i smallest of the whole array, just the first i values, sorted among themselves. Later keys can still land in front of them and push them right.
- Start.
i = 1: a prefix of one value is sorted. - Step. The shift loop moves every prefix value bigger than the key one place right, which keeps them in order. The remaining values are all
<= key, so putting the key right after them keeps the prefix sorted, nowi + 1long. - End. When
i = n, the prefix is the whole array.
Shifting, not swapping
A simpler version swaps the key leftwards one neighbour at a time. It sorts the same way but writes three times per step (or two slots, with a temporary variable). The shifting version holds the key aside and writes once per moved value, then once more to drop the key. On a reversed array of 8 values that is 28 + 7 = 35 writes, instead of 56 slot writes for the swapping version. It also explains the first line of the loop body: the key must be saved in key, because the first shift overwrites values[i].
Complexity
- Worst: O(n²). On a reversed array every pair is an inversion, so key number
iis compared with and shifted past allivalues before it:n(n - 1) / 2comparisons and shifts, 28 each forn = 8. - Best: O(n). On a sorted array each key is compared once with its left neighbour, finds it is not bigger, and stops:
n - 1comparisons and no shifts. - Nearly sorted: O(n + inversions). The shifts equal the inversions, and the comparisons are at most one more per key. If every value is within
kplaces of its final spot, the running time is O(nk). This is the real reason insertion sort matters: its cost follows how disordered the input is, not just how long. - Space: O(1). It works in place with a key and two indexes.
- Stable. The comparison is strict (
>), so a value equal to the key is never shifted past it, and equal values keep their original order. Switch to>=and the key jumps in front of its equals: still sorted, no longer stable, and extra shifts for nothing.
Common bugs
- Forgetting to save the key. Without
key, the first shift overwritesvalues[i]and the value you wanted to insert is lost. - Checking
values[j]beforej >= 0. Reverse the two conditions andvalues[-1]is read, which isundefinedin JavaScript (so the comparison is quietly false), undefined behaviour in C++ and anArrayIndexOutOfBoundsExceptionin Java. Python would silently read the last element and give wrong results. The bounds check goes first. - Dropping the key at
jinstead ofj + 1. The loop stops one place before the gap, so the key belongs atj + 1. - Starting at
i = 0. It still works, but the first pass does nothing. Starting at 1 says: a single value is already sorted. - Using
>=instead of>. It sorts, but breaks stability and moves equal values for nothing. - Unsigned indexes in C++.
j >= 0is always true forstd::size_t, andjwraps around at the front. The listing usesintfor that reason.
When to use it (and when not)
Use it for small arrays, for arrays that are nearly sorted, and when the data arrives one value at a time and you must keep it sorted (an "online" sort: insert each new value into the sorted list). It's also the simplest stable in-place sort that is actually fast on the inputs where it makes sense.
For big, random input, don't: a thousand shuffled values mean around 250,000 shifts, against roughly ten thousand comparisons for merge sort or quick sort.
Yet insertion sort is hiding inside the sorts you use every day. TimSort (Python's sorted, Java's object sort) cuts the array into short runs and uses a binary insertion sort to grow each run to a minimum length before merging. Introsort (C++'s std::sort in common implementations) and many quick sort variants stop recursing once a part is about 16 elements and finish it with insertion sort. For a handful of values, the low overhead and the cache-friendly, sequential memory access beat the O(n log n) algorithms' bookkeeping.
Interview variations
- Binary insertion sort. The prefix is sorted, so find the gap by binary search instead of walking: O(log i) comparisons per key, O(n log n) in total. The shifts are still there, so the time stays O(n²), but it pays off when comparing is expensive and moving is cheap. Use the upper bound (after the last equal value) to keep it stable.
- Insertion sort on a linked list. Inserting costs O(1) once you've found the spot, so there are no shifts, but the search is a linear walk, so it's still O(n²).
- Count the inversions. The number of shifts is the inversion count. Counting them in O(n log n) takes a merge sort, which is a classic interview question.
- Sort a nearly sorted array where every value is at most
kplaces from its final position. Insertion sort does it in O(nk); a heap of sizek + 1does it in O(n log k). - Shell sort. Insertion sort on values
hplaces apart for a shrinkingh, so that values travel far in one shift. It ends with a plain insertion sort on an array that is already almost sorted.
Code
The same algorithm, step for step, in 4 languages.
// Insertion sort: grow a sorted prefix one element at a time, like sorting a hand of cards.
// Take the next value as the key, shift the bigger values of the prefix one place right,
// then drop the key into the gap.
/**
* Sorts `values` in ascending order, in place.
* Stable: only a strictly bigger value is shifted past the key, so equals keep their order.
*
* @param {number[]} values the array to sort
* @returns {void}
*/
export function insertionSort(values) {
for (let i = 1; i < values.length; i++) {
const key = values[i]; // the next card to place; values[0..i) is already sorted
let j = i - 1;
while (j >= 0 && values[j] > key) {
values[j + 1] = values[j]; // shift the bigger value one place right
j--;
}
values[j + 1] = key; // drop the key into the gap
}
}
# Insertion sort: grow a sorted prefix one element at a time, like sorting a hand of cards.
# Take the next value as the key, shift the bigger values of the prefix one place right,
# then drop the key into the gap.
from typing import List
def insertion_sort(values: List[int]) -> None:
"""Sort values in ascending order, in place.
Stable: only a strictly bigger value is shifted past the key, so equals keep their order.
"""
for i in range(1, len(values)):
key = values[i] # the next card to place; values[0..i) is already sorted
j = i - 1
while j >= 0 and values[j] > key:
values[j + 1] = values[j] # shift the bigger value one place right
j -= 1
values[j + 1] = key # drop the key into the gap
/**
* Insertion sort: grow a sorted prefix one element at a time, like sorting a hand of cards.
* Take the next value as the key, shift the bigger values of the prefix one place right,
* then drop the key into the gap.
*/
public final class InsertionSort {
private InsertionSort() {
}
/**
* Sorts values in ascending order, in place.
* Stable: only a strictly bigger value is shifted past the key, so equals keep their order.
*/
public static void insertionSort(int[] values) {
for (int i = 1; i < values.length; i++) {
int key = values[i]; // the next card to place; values[0..i) is already sorted
int j = i - 1;
while (j >= 0 && values[j] > key) {
values[j + 1] = values[j]; // shift the bigger value one place right
j--;
}
values[j + 1] = key; // drop the key into the gap
}
}
}
// Insertion sort: grow a sorted prefix one element at a time, like sorting a hand of cards.
// Take the next value as the key, shift the bigger values of the prefix one place right,
// then drop the key into the gap.
#include <vector>
// Sorts values in ascending order, in place.
// Stable: only a strictly bigger value is shifted past the key, so equals keep their order.
void insertionSort(std::vector<int>& values) {
int n = static_cast<int>(values.size());
for (int i = 1; i < n; i++) {
int key = values[i]; // the next card to place; values[0..i) is already sorted
int j = i - 1;
while (j >= 0 && values[j] > key) {
values[j + 1] = values[j]; // shift the bigger value one place right
j--;
}
values[j + 1] = key; // drop the key into the gap
}
}
Test yourself
10 quick questions to check it stuck.
Q1 · Insertion sort has inserted the keys at i = 1, 2 and 3 of [5, 2, 8, 1, 7, 3, 6, 4]. What does the array look like now?
Take it further
- Animation
Insertion Sort Animation
A card lifted out of the row, bigger bars sliding right underneath, a gap that travels left: insertion sort as shifting, never swapping
Free
