AlgoViz

Insertion sort

easy 14 min

Insertion 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

0:00 / 5:10

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.

Step 1 of 3

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:

PassKeyWhat movesArray after the pass
startnothing, [5] is sorted on its own5 | 2, 4, 1, 3
122<52 < 5: shift 5 right2, 5 | 4, 1, 3
244<54 < 5: shift 5 right; 2≤42 \le 4 stop2, 4, 5 | 1, 3
311 is smallest: shift 5, 4 and 2 right1, 2, 4, 5 | 3
43shift 5 and 4; 2≤32 \le 3 stop, insert between 2 and 41, 2, 3, 4, 5
The bar marks the boundary. Left of it is sorted; right of it has not been looked at yet.
SCIP: the four beats of every pass
  1. 1ScanSelect the next unsorted value
  2. 2CompareAgainst the sorted part, right to left
  3. 3InsertInto the gap left by the shifts
  4. 4ProgressMove the boundary and repeat
Repeat: back to Scan

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]

Two ways out of the loop: run off the left edge (the key is the smallest so far) or meet a value that is not bigger.
Python
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]
The whole algorithm. The key is held aside so each shift is one write.
Edit and run it in your browser

Worked example

Sorting [5, 2, 9, 1, 5]

  1. 1

    Start: [5] is sorted

    Sorted part [5], unsorted part [2, 9, 1, 5].

  2. 2

    Key 2

    2<52 < 5, so shift 5 right and insert 2. Sorted [2, 5], unsorted [9, 1, 5].

  3. 3

    Key 9

    9>59 > 5 on the first comparison: no shift. The best case for one key. Sorted [2, 5, 9].

  4. 4

    Key 1

    1<91 < 9, 1<51 < 5, 1<21 < 2: shift all three and insert 1 at the front. The worst case for one key. Sorted [1, 2, 5, 9].

  5. 5

    Key 5

    5<95 < 9, shift 9. Then 5≤55 \le 5, stop, and insert after the existing 5. Result [1, 2, 5, 5, 9].

KeyComparisonsShifts
211
910
133
521
total75
Five shifts, and the input has exactly five out-of-order pairs: (5, 2), (5, 1), (2, 1), (9, 1), (9, 5).

Correctness

The loop invariant

Why does this always work? At the start of every pass ii, 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

arr[0]≤arr[1]≤⋯≤arr[i−1],{arr[0..i−1]}={original[0..i−1]}\text{arr}[0] \le \text{arr}[1] \le \dots \le \text{arr}[i-1], \qquad \{\text{arr}[0..i-1]\} = \{\text{original}[0..i-1]\}
It holds at i=1i = 1 (one value is sorted). Each pass inserts one value without breaking the order, so it holds at i+1i + 1. When i=ni = n the whole array is sorted.

Initialise, maintain, terminate

The same three-part argument proves most loop-based algorithms correct.

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

Cbest(n)=1+1+⋯+1⏟n−1 passes=n−1=O(n),shifts=0C_{\text{best}}(n) = \underbrace{1 + 1 + \dots + 1}_{n-1 \text{ passes}} = n - 1 = O(n), \qquad \text{shifts} = 0
Sorting [1, 2, 3, 4, 5] takes the minimum possible: 4 comparisons. You cannot confirm order with fewer, because every neighbouring pair must be checked.

Complexity

Worst case: n(n-1)/2 shifts

On reversed input every key is the smallest so far, so pass ii shifts all ii values in front of it. Adding the passes is an arithmetic series.

Reversed input

Sworst(n)=∑i=1n−1i=1+2+⋯+(n−1)=n(n−1)2=O(n2)S_{\text{worst}}(n) = \sum_{i=1}^{n-1} i = 1 + 2 + \dots + (n-1) = \frac{n(n-1)}{2} = O(n^2)
For [5, 4, 3, 2, 1] that is 5⋅42=10\frac{5 \cdot 4}{2} = 10 shifts; for 7 reversed values, 21. Comparisons are the same count.
nBest: comparisons n−1n-1Average: about n(n−1)4\frac{n(n-1)}{4}Worst: n(n−1)2\frac{n(n-1)}{2}
109about 2345
2019about 95190
10099about 2,4754,950
1,000999about 249,750499,500
Doubling nn roughly quadruples the worst case: the signature of quadratic time. Space stays O(1)O(1): only key and j.

The math

Inversions: the exact cost

An inversion is a pair of positions i<ji < j with ai>aja_i > a_j: 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

shifts=I(a)=#{(i,j):i<j, ai>aj},comparisons≤I(a)+(n−1)\text{shifts} = I(a) = \#\{(i, j) : i < j,\ a_i > a_j\}, \qquad \text{comparisons} \le I(a) + (n - 1)
Each pass makes one comparison per shift plus at most one more that stops it. So insertion sort runs in O(n+I)O(n + I): linear when II is small, quadratic when II is close to its maximum.

Range and average

0≤I(a)≤(n2)=n(n−1)2,E[I]=12(n2)=n(n−1)40 \le I(a) \le \binom{n}{2} = \frac{n(n-1)}{2}, \qquad \mathbb{E}[I] = \frac{1}{2}\binom{n}{2} = \frac{n(n-1)}{4}
Sorted input has 0 inversions, reversed has all of them. In a random order each pair is inverted with probability 12\frac12, so the average is half the maximum: still O(n2)O(n^2).

Head to head

Insertion vs bubble vs selection

PropertyInsertion sortSelection sortBubble sort
Best timeO(n)O(n)O(n2)O(n^2)O(n)O(n) with an early-exit flag
Worst timeO(n2)O(n^2)O(n2)O(n^2)O(n2)O(n^2)
SpaceO(1)O(1)O(1)O(1)O(1)O(1)
StableYesNoYes
AdaptiveYesNoOnly with the flag
Writesone per inversionat most n−1n - 1 swapsone swap per inversion
Best useSmall or nearly sorted dataWhen writes are expensiveTeaching
On [5, 2, 9, 1]: insertion 5 comparisons and 4 shifts, bubble 6 comparisons and 4 swaps, selection 6 comparisons and 2 swaps.

Which simple sort?

Among the quadratic sorts, insertion sort is almost always the right pick. Bubble sort does the same swaps with more comparisons.

Variants

Binary insertion, Shell sort and linked lists

  • Binary insertion sort

    Find the spot with binary search: O(log⁡i)O(\log i) comparisons per key, O(nlog⁡n)O(n \log n) total. Shifts are still O(n2)O(n^2), 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 O(n2)O(n^2) 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.

Python
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]
Binary insertion sort with bisect: fewer comparisons, same shifts.
Edit and run it in your browser

Pattern spotting

When to reach for it

Good for

  • Small arrays, roughly under 50 values.
  • Nearly sorted data: O(n)O(n) 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 O(nlog⁡n)O(n \log n) 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

For tiny inputs the constant factors win: insertion sort has no recursion and no extra memory, so it beats O(nlog⁡n)O(n \log n) sorts below a few dozen values.
  • 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 O(n)O(n) on sorted input (n−1n - 1 comparisons, 0 shifts); worst case n(n−1)2\frac{n(n-1)}{2} shifts on reversed input; average n(n−1)4\frac{n(n-1)}{4}.
  • Shifts equal the number of inversions, so the running time is O(n+I)O(n + I).
  • Stable (use > not >=), in place (O(1)O(1) 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.

Sources