Insertion sort grows a sorted prefix one element at a time: it takes the next element and slides it left past every larger value until it fits. It is O(n²) in the worst case, but its running time is really O(n + number of inversions), so it is nearly linear on almost-sorted data. Stable, in-place, online and with a tiny inner loop, it is the algorithm production libraries such as Timsort and introsort use for short subarrays.
Think of it like
Sorting a hand of playing cards
You pick up cards one at a time. Your hand is always sorted, and each new card is slid into place by moving it left past the cards that are bigger than it. If the dealer happens to hand you cards in nearly the right order, each card needs to move only a little, and sorting your hand takes almost no effort.
How it works
Before step i, the prefix a[0..i-1] is sorted. Save key = a[i], then walk left from j = i - 1: while a[j] > key, copy a[j] one slot to the right. When you meet a value <= key (or the start of the array), drop key into the gap.
- 1
Pick the key
Take
key = a[i], the first element of the unsorted part. Its slot is now free to be overwritten. - 2
Shift larger values right
While
j >= 0anda[j] > key, seta[j + 1] = a[j]and decrementj. These are shifts, not swaps: one write each. - 3
Insert
Write
a[j + 1] = key. The prefixa[0..i]is sorted again. - 4
Repeat
Move on to
i + 1until the whole array is the sorted prefix.
Worked example
| i | Key | Shifted values | Array after insertion | Shifts |
|---|---|---|---|---|
| 1 | 2 | 5 | [2, 5, 4, 6, 1, 3] | 1 |
| 2 | 4 | 5 | [2, 4, 5, 6, 1, 3] | 1 |
| 3 | 6 | none | [2, 4, 5, 6, 1, 3] | 0 |
| 4 | 1 | 6, 5, 4, 2 | [1, 2, 4, 5, 6, 3] | 4 |
| 5 | 3 | 6, 5, 4 | [1, 2, 3, 4, 5, 6] | 3 |
[5, 2, 4, 6, 1, 3] takes 9 shifts, which is exactly the number of inversions in the input.Adaptive analysis via inversions
An inversion is a pair of positions i < j with a[i] > a[j]: two elements in the wrong order. Shifting the key past one larger neighbor fixes exactly one inversion and creates none, so the total number of shifts equals the number of inversions I. Each iteration also makes at most one comparison that does not cause a shift (the one that stops it).
| Input | Inversions I | Time |
|---|---|---|
| Already sorted | 0 | Θ(n): one comparison per element |
| Each element at most k places from its final position | ≤ n·k | O(n·k) |
| A few elements out of place | O(n) | O(n) |
| Random permutation | n(n − 1)/4 on average | Θ(n²) |
| Reverse sorted | n(n − 1)/2 | Θ(n²) |
Binary insertion sort
The prefix is sorted, so the insertion point can be found with Binary Search in O(log i) comparisons instead of a linear walk. That cuts comparisons to O(n log n) overall. The catch: the elements after the insertion point still have to be shifted, so the number of moves stays Θ(n²) in the worst case and the running time is still O(n²).
Helps when
- Comparisons are expensive (long strings, user-defined comparators, Python objects)
- Moves are cheap block copies (
memmove,System.arraycopy) - Arrays are short, as in Timsort's runs
Does not help
- Worst-case time: still O(n²) because of the shifts
- Nearly-sorted input: the linear walk already stops after one comparison, while binary search always costs log i
The online property
An online algorithm can process its input piece by piece without seeing the whole input first. Insertion sort is online: after each new element arrives, everything received so far is sorted. That makes it a natural fit for keeping a small leaderboard sorted as scores arrive, or for maintaining a sorted buffer of recent events. Selection sort, by contrast, needs the entire input before it can pick the first minimum.
import bisect
scores: list[int] = []
for s in [42, 17, 99, 63, 17]:
bisect.insort(scores, s) # binary search + shift: O(log n) compares, O(n) moves
print(scores) # always sorted after each arrivalWhy hybrid sorts use it for small subarrays
For small n, constant factors beat asymptotics. Insertion sort has no recursion, no extra memory, a branch-predictable inner loop and perfectly sequential memory access. Below a threshold of a few dozen elements it outruns Merge Sort and Quick Sort, so production sorts switch to it for short pieces.
| Library sort | How insertion sort is used |
|---|---|
Timsort (Python list.sort, Java object sorts) | Binary insertion sort extends short natural runs to a minimum length minrun (32 to 64 in CPython) before merging |
C++ std::sort (libstdc++ introsort) | Quick sort stops on subarrays of 16 or fewer elements; one final insertion sort pass finishes the whole array |
Java Arrays.sort for primitives (dual-pivot quick sort) | Insertion sort for tiny subarrays (below 47 elements in JDK 7 and 8) |
Shell sort: insertion sort with long jumps
Insertion sort's weakness is that elements move only one slot per shift: a small value at the far right needs n shifts. Shell sort (Donald Shell, 1959) first runs insertion sort on elements that are gap apart, for a decreasing sequence of gaps. Large gaps move elements long distances cheaply; the final pass with gap = 1 is an ordinary insertion sort on data that is now nearly sorted, so it is fast.
- 1
Pick a gap sequence
For example Knuth's
1, 4, 13, 40, 121, …(each term is 3h + 1), starting from the largest gap below n/3. - 2
Gap-sort
For the current gap h, insertion-sort each of the h interleaved subsequences
a[r], a[r+h], a[r+2h], …. The array becomes h-sorted. - 3
Shrink the gap
Move to the next smaller gap. An h-sorted array stays h-sorted after a smaller gap pass, so progress accumulates.
- 4
Finish with gap 1
The last pass is plain insertion sort, which guarantees a correctly sorted result whatever came before.
| Gap sequence | Values | Worst case |
|---|---|---|
| Shell (1959) | n/2, n/4, …, 1 | O(n²) |
| Knuth | 1, 4, 13, 40, 121, … = (3ᵏ − 1)/2 | O(n^1.5) |
| Sedgewick (1986) | 1, 8, 23, 77, 281, … | O(n^(4/3)) |
| Pratt (1971) | all 2ᵖ3^q: 1, 2, 3, 4, 6, 8, 9, 12, … | O(n log² n), but many passes |
| Ciura (2001) | 1, 4, 10, 23, 57, 132, 301, 701 | Unknown; best known in practice |
Complexity
| Case | Time | Space | Notes |
|---|---|---|---|
| Best | O(n) | O(1) | Already sorted: n − 1 comparisons, no shifts |
| Nearly sorted | O(n·k) | O(1) | Every element within k positions of its final place |
| Average | O(n²) | O(1) | About n²/4 shifts on a random permutation |
| Worst | O(n²) | O(1) | Reverse sorted: n(n − 1)/2 shifts |
| Binary insertion sort | O(n²) | O(1) | O(n log n) comparisons, but still O(n²) moves |
Stable, in-place, adaptive (Θ(n + inversions)) and online.
Implementation
Holds the key aside and shifts larger elements right, then writes the key once.
def insertion_sort(a: list[int]) -> list[int]:
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key: # strict > keeps equal keys in order (stable)
a[j + 1] = a[j] # shift right
j -= 1
a[j + 1] = key # drop the key into the gap
return aKey takeaways
- Insertion sort grows a sorted prefix by shifting larger elements right and dropping each key into the gap.
- Its running time is Θ(n + I), where I is the number of inversions: O(n) on sorted or nearly-sorted data, O(n²) on reversed or random data.
- It is stable, in-place and online, with very low overhead, which is why Timsort and introsort use it for small subarrays.
- Binary insertion sort reduces comparisons to O(n log n) but still needs O(n²) moves in the worst case.
- Shell sort runs insertion sort over shrinking gaps to move elements long distances, reaching about O(n^1.5) or better.
Common pitfalls
- Using
>=instead of>in the inner loop, which moves equal keys past each other and breaks stability. - Swapping at every step instead of shifting, which triples the number of writes.
- Claiming binary insertion sort is O(n log n): only the comparisons are; the shifts keep it O(n²).
- Forgetting the
j >= 0bound check, which readsa[-1](or wraps around in Python) when the key is the new minimum.
Interview tips
- Explain the inversion argument: each shift removes exactly one inversion, so time is Θ(n + I).
- When an input is described as "nearly sorted" or "each element is at most k positions away", insertion sort (O(nk)) or a size-k heap (O(n log k)) is the expected answer.
- Be ready to implement it on a linked list (LeetCode 147), where insertion needs no shifting at all.
Real-world applications
- Small-array base case inside Timsort, introsort and dual-pivot quick sort.
- Keeping a small, continuously updated list sorted (leaderboards, recent events, sliding windows).
- Finishing a nearly-sorted dataset, for example after appending a few new records to a sorted file.
- Embedded systems that need a tiny, in-place, non-recursive sort.
Practice problems
Test yourself
Insertion sort runs on [2, 1, 4, 3, 6, 5]. How many shifts does it perform?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.