algossorting

insertion sort

take the next item and slide it back to where it belongs, like cards in a hand.

report a mistake
.md

keep the front of the array sorted. hold the next item, shift every bigger item one slot to the right, and drop it into the gap.

time
O(n²) random or reversed input
sorted input
O(n) n - 1 comparisons, no shifts
nearly sorted
O(n + k) k pairs out of order, one shift each
space
O(1) in place, one item in hand
stable
yes an equal item never passes another
reach for it
  • small arrays, a few dozen items or fewer
  • the last step inside faster sorts
  • input that's already nearly sorted
  • items arriving one at a time into a sorted list
on this page
  1. the idea
  2. watch it run
  3. try it
  4. pseudocode
  5. the shift, up close
  6. complexity
  7. implementations
  8. pitfalls
  9. variants
  10. practice
  11. how real libraries do it
  12. sources

insertion sort keeps the front of the array sorted and grows it by one item at a time. hold the next item, shift every bigger item one slot to the right, and drop it into the gap. it’s how most people sort a hand of cards. on a big random array it’s slow, about n²/4 comparisons, but it’s short, in place and stable, and on input that’s nearly sorted it’s as fast as anything. that’s why the faster sorts hand their small pieces to it.

the idea

the array has two parts: a sorted front, and the rest. each pass takes the first item of the rest and slides it left past every bigger item, until it meets one that isn’t. the sorted part grows by one, and after n - 1 passes it’s the whole array. here it is on the same eight numbers as the merge sort page:1

eight numbers. the first one, 38, counts as sorted on its own: a run of one. everything right of it is still to do.

an animation in six steps: eight numbers, 38, 27, 43, 3, 9, 82, 10 and 19, in a row, with a count of shifts and comparisons under them. the sorted front is outlined cyan, the rest amber, and the item in hand is white and lifted above the row. 27 lifts out, 38 slides right into its gap, and 27 drops in at the front. 43 lifts out and drops straight back, since 38 isn't bigger. 3 lifts out, 43, 38 and 27 slide right one after another, and 3 drops in at the front. 9 slides past 43, 38 and 27 and stops behind 3. 82 stays. then 10 and 19 each slide past 82, 43, 38 and 27, and stop behind 9 and 10. the row ends 3, 9, 10, 19, 27, 38, 43, 82, after 15 shifts and 20 comparisons.

watch it run

step through a real run. the sorted front is cyan, under a bracket, and the rest is amber. the item in hand is white, sitting in its gap, and the bar with a white ring is the one being compared or shifted. the pseudocode follows along, with a count of comparisons and shifts.

input

8 items. the first, 38, is a sorted run of one on its own

comparisons
0
shifts
0
step
1 of 53
pseudocode
insertion_sort(a):  for i in range(1, len(a)):  # a[:i] is sorted    x = a[i]  # hold the next item    j = i  # the gap it left    while j > 0 and a[j - 1] > x:  # a bigger item on the left?      a[j] = a[j - 1]  # shift it right, into the gap      j -= 1    a[j] = x  # drop x into the gap

an interactive stepper: bars for an array, the page's eight numbers first, sorted a pass at a time. a picker switches the input between shuffled, sorted and reversed, another between 8, 12, 16 and 32 bars, and a button deals a new array. the sorted front is cyan under a bracket, the rest amber, the item in hand white in its gap, and the bar being compared or shifted has a white ring. i marks the pass and j the gap. the matching pseudocode line is highlighted, with counters for comparisons and shifts.

pick reversed and every item slides all the way to the front. pick sorted and every pass is one comparison and no shift.

try it

every pass is the same decision made over and over: is the item on the left bigger? predict where the held item ends up, and what it costs to get there.

hold 9. which slot does it drop into?

tap a slot.

0 / 0 right

a practice exercise on a row of numbers with its sorted front in cyan and the item in hand in white. some questions hold the next item and ask which slot it drops into, answered by tapping a slot, or how many items shift right to make room, or how many comparisons find its slot. others show a short unsorted array and ask how many shifts the whole sort makes: one per pair out of order.

pseudocode

pseudocode
insertion_sort(a):
  for i in range(1, len(a)):  # a[:i] is sorted
    x = a[i]  # hold the next item
    j = i  # the gap it left
    while j > 0 and a[j - 1] > x:  # a bigger item on the left?
      a[j] = a[j - 1]  # shift it right, into the gap
      j -= 1
    a[j] = x  # drop x into the gap

a[j - 1] > x is strict. an item equal to x doesn’t shift, so x stays to its right, and equal items keep their order: that’s what makes the sort stable. the j > 0 check is the wall. an item smaller than everything before it shifts all of them, and the gap reaches the front with nothing left to compare.

the shift, up close

sorted: 7 comparisons, 0 shifts0 pairs out of order

two neighbors swapped: 9 comparisons, 2 shifts2 pairs out of order

the page's eight: 20 comparisons, 15 shifts15 pairs out of order

reversed: 28 comparisons, 28 shifts28 pairs out of order

four rows of eight numbers, each sorted by insertion sort with its comparisons and shifts counted, and an arc under every pair that starts out in the wrong order. sorted, 1 to 8: 7 comparisons, no shifts, no arcs. 1 to 8 with two neighboring pairs swapped, 6 before 5 and 8 before 7: 9 comparisons and 2 shifts, one arc each. the page's eight numbers: 20 comparisons and 15 shifts, 15 arcs. reversed, 8 down to 1: 28 comparisons and 28 shifts, an arc for every pair.

complexity

inputcomparisonsshifts
sortedn - 10
nearly sortedabout n + kk
randomabout n²/4about n²/4
reversedn(n - 1)/2n(n - 1)/2

O(n²) on random or reversed input, O(n) on sorted input, and O(n + k) in between, where k is the number of pairs out of order: k shifts exactly, and at most k + n - 1 comparisons. the work follows the pairs out of order, not the size. space is O(1): one item in hand, and the array is sorted where it sits.

input
020k40k60k80k100k162564096insertion sort
insertion sort
4,255,320 comparisons
merge sort
43,932 comparisons
quicksort
59,922 comparisons
heap sort
85,650 comparisons

a line chart of comparisons against items, from 16 to 4,096 on a doubling scale, for insertion sort, merge sort, quicksort and heap sort on the same arrays, with a picker for the input: shuffled, already sorted or reversed. on shuffled input insertion sort, in cyan, climbs off the top of the chart, at 100,000, before 1,024 items: 273,132 there and 4,255,320 at 4,096, while merge sort, dashed, quicksort, dotted, and heap sort, muted, stay low: 8,962, 11,185 and 17,273 at 1,024, and 43,932, 59,922 and 85,650 at 4,096. on sorted input insertion sort is the lowest line, n - 1: 1,023 at 1,024 against 5,120, 8,204 and 18,060. reversed, it's every pair: 523,776 at 1,024, against 5,120, 8,601 and 16,407. a slider picks a size and reads off all four.

on 1,024 shuffled numbers insertion sort made 273,132 comparisons. merge sort made 8,962 on the same ones, quicksort 11,185 and heap sort 17,273: the n log n sorts are 16 to 30 times cheaper by then, and the gap keeps opening, since insertion sort’s work roughly quadruples each time the input doubles and theirs only a bit more than doubles. at 4,096 it’s 4,255,320 against merge sort’s 43,932. on sorted input it’s the other way round: 1,023 comparisons, n - 1, against 5,120 for merge sort, 8,204 for quicksort and 18,060 for heap sort, which split, partition and sift whatever the order. reversed is insertion sort’s worst case, every pair: 523,776.

implementations

each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest): the same seven tests in every language, including 2000 seeded arrays against the language’s own sort, a million sorted items in 999,999 comparisons, 1,024 reversed in 523,776, and on every random array the count that the shifts are the pairs out of order, and the comparisons one more per pass that stops short of the front. every tab holds the item, shifts the bigger ones right and stops at an equal item, so all six are stable. each takes an order: a compare function in typescript, go (SortFunc), rust (insertion_sort_by), swift (by:) and c (insertion_sort_by, with a context pointer for anything the comparison keeps, like a count), and a key function in python.

go/algos/insertionsort/insertionsort.go
// Package insertionsort is a reference insertion sort, in place and stable. each pass holds the next item,
// shifts every bigger item one slot to the right, and drops the held item into the gap. sorted input costs
// n - 1 comparisons and no shifts. reversed input costs n(n - 1) / 2 of each. the shifts are exactly the
// pairs out of order, so nearly sorted input stays cheap.
package insertionsort

import "cmp"

// Sort sorts s in ascending order.
func Sort[S ~[]E, E cmp.Ordered](s S) {
	SortFunc(s, cmp.Compare[E])
}

// SortFunc sorts s by compare, which returns a negative number when a goes before b, a positive one when
// it goes after, and 0 for a tie. Ties keep their original order: the sort is stable.
func SortFunc[S ~[]E, E any](s S, compare func(a, b E) int) {
	for i := 1; i < len(s); i++ {
		x := s[i] // hold the next item. s[:i] is sorted already
		j := i    // the gap it left
		// a bigger item on the left shifts right, into the gap. > stops at an equal item, so x stays
		// behind it: that's what keeps the sort stable
		for j > 0 && compare(s[j-1], x) > 0 {
			s[j] = s[j-1]
			j--
		}
		s[j] = x // drop x into the gap
	}
}
rust/algos/src/insertion_sort.rs
//! insertion sort, in place and stable. each pass holds the next item, shifts every bigger item one slot to the right, and drops the held item into the gap. sorted input costs n - 1 comparisons and no shifts. reversed input costs n(n - 1) / 2 of each. the shifts are exactly the pairs out of order, so nearly sorted input stays cheap.

use std::cmp::Ordering;

/// Sorts `v` in ascending order, keeping equal items in their original order.
pub fn insertion_sort<T: Ord + Clone>(v: &mut [T]) {
    insertion_sort_by(v, |a, b| a.cmp(b));
}

/// Sorts `v` with `cmp`, keeping equal items in their original order. A panicking `cmp` can
/// leave one item in `v` twice and the held one gone: the standard library's insertion sort
/// has a drop guard that writes the held item back.
pub fn insertion_sort_by<T: Clone, F: FnMut(&T, &T) -> Ordering>(v: &mut [T], mut cmp: F) {
    for i in 1..v.len() {
        let x = v[i].clone(); // hold the next item. v[..i] is sorted already
        let mut j = i; // the gap it left
        // a bigger item on the left shifts right, into the gap. `Greater` stops at an equal item,
        // so x stays behind it: that's what keeps the sort stable
        while j > 0 && cmp(&v[j - 1], &x) == Ordering::Greater {
            v[j] = v[j - 1].clone();
            j -= 1;
        }
        v[j] = x; // drop x into the gap
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// 1 to n, in order.
    fn sorted(n: i32) -> Vec<i32> {
        (1..=n).collect()
    }

    /// n down to 1.
    fn reversed(n: i32) -> Vec<i32> {
        (1..=n).rev().collect()
    }

    /// Comparisons and shifts on one input, counted through the comparator: every call is a
    /// comparison, and a call that answers "bigger" is a shift.
    fn count(values: &[i32]) -> (usize, usize) {
        let (mut comparisons, mut shifts) = (0, 0);
        let mut v = values.to_vec();
        insertion_sort_by(&mut v, |x, y| {
            comparisons += 1;
            if x > y {
                shifts += 1;
            }
            x.cmp(y)
        });
        (comparisons, shifts)
    }

    /// The pairs out of order: i before j with a[i] > a[j]. Insertion sort undoes each one with
    /// exactly one shift.
    fn inversions(a: &[i32]) -> usize {
        (0..a.len())
            .map(|j| a[..j].iter().filter(|&&v| v > a[j]).count())
            .sum()
    }

    /// Items smaller than everything before them, not counting the first: the ones that slide all
    /// the way to the front, where the gap stops the pass with no comparison.
    fn new_lows(a: &[i32]) -> usize {
        (1..a.len())
            .filter(|&j| a[..j].iter().all(|&v| a[j] < v))
            .count()
    }

    // the page's eight numbers
    const PAGE: [i32; 8] = [38, 27, 43, 3, 9, 82, 10, 19];

    #[test]
    fn sorts_each_case_in_place() {
        let cases: [(&str, &[i32], &[i32]); 6] = [
            (
                "the page's eight numbers",
                &PAGE,
                &[3, 9, 10, 19, 27, 38, 43, 82],
            ),
            ("empty", &[], &[]),
            ("one item", &[5], &[5]),
            ("already sorted", &[1, 2, 3, 4], &[1, 2, 3, 4]),
            ("reversed", &[4, 3, 2, 1], &[1, 2, 3, 4]),
            ("duplicates", &[3, 1, 3, 1], &[1, 1, 3, 3]),
        ];
        for (name, input, want) in cases {
            let mut v = input.to_vec();
            insertion_sort(&mut v);
            assert_eq!(v, want, "{name}");
        }
    }

    #[test]
    fn sorts_ascending_by_default_and_by_the_comparator_when_given_one() {
        let mut a = [3, 1, 2];
        insertion_sort(&mut a);
        assert_eq!(a, [1, 2, 3]);
        let mut b = [1, 3, 2];
        insertion_sort_by(&mut b, |x, y| y.cmp(x));
        assert_eq!(b, [3, 2, 1]);
    }

    #[test]
    fn is_stable_equal_keys_keep_their_original_order() {
        let mut pairs = [(2, 'a'), (1, 'b'), (2, 'c'), (1, 'd')];
        insertion_sort_by(&mut pairs, |x, y| x.0.cmp(&y.0));
        let ids: Vec<char> = pairs.iter().map(|p| p.1).collect();
        assert_eq!(ids, ['b', 'd', 'a', 'c']);
    }

    #[test]
    fn comparisons_n_minus_1_sorted_n_times_n_minus_1_over_2_reversed_20_on_the_pages_eight_numbers()
     {
        assert_eq!(count(&sorted(100)), (99, 0));
        assert_eq!(count(&reversed(100)), (4950, 4950));
        assert_eq!(count(&PAGE), (20, 15));
    }

    #[test]
    fn reversed_1024_items_523776_comparisons_and_as_many_shifts_the_worst_case() {
        assert_eq!(count(&reversed(1024)), (523_776, 523_776));
    }

    #[test]
    fn a_million_items_already_sorted_999999_comparisons_one_per_item_after_the_first_and_no_shifts()
     {
        assert_eq!(count(&sorted(1_000_000)), (999_999, 0));
    }

    #[test]
    fn agrees_with_the_built_in_sort_on_2000_seeded_arrays_and_the_work_is_the_pairs_out_of_order()
    {
        // xorshift32 seeded with 42, like the other tests here
        let mut state: u32 = 42;
        let mut next = || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        };
        for _ in 0..2000 {
            let n = next() % 40;
            // small values, so most arrays have ties
            let values: Vec<i32> = (0..n).map(|_| (next() % 20) as i32).collect();
            let mut got = values.clone();
            insertion_sort(&mut got);
            let mut want = values.clone();
            want.sort();
            assert_eq!(got, want);
            // every shift undoes one pair out of order. each shift comes with a comparison, and
            // every pass ends with one more, the one that finds an item that doesn't move, unless
            // the gap reaches the front first
            let (comparisons, shifts) = count(&values);
            let pairs = inversions(&values);
            assert_eq!(shifts, pairs);
            assert_eq!(comparisons, pairs + n.saturating_sub(1) - new_lows(&values));
        }
    }
}
site/src/visuals/insertion-sort/insertion-sort.ts
const ascending = <T>(a: T, b: T) => (a < b ? -1 : a > b ? 1 : 0);

/**
 * Insertion sort, in place and stable. Each pass holds the next item, shifts every bigger item one slot to the
 * right, and drops the held item into the gap. Sorted input costs n - 1 comparisons and no shifts. Reversed input
 * costs n(n - 1) / 2 of each. The shifts are exactly the pairs out of order, so nearly sorted input stays cheap.
 */
export function insertionSort<T>(a: T[], compare: (a: T, b: T) => number = ascending): void {
  for (let i = 1; i < a.length; i++) {
    const x = a[i]; // hold the next item. a[0:i] is sorted already
    let j = i; // the gap it left
    // a bigger item on the left shifts right, into the gap. `>` stops at an equal item, so x stays behind it:
    // that's what keeps the sort stable
    while (j > 0 && compare(a[j - 1], x) > 0) {
      a[j] = a[j - 1];
      j--;
    }
    a[j] = x; // drop x into the gap
  }
}
c/algos/insertion_sort.c
/* insertion sort, in place and stable. each pass holds the next item, shifts every bigger item one slot to the right, and drops the held item into the gap. sorted input costs n - 1 comparisons and no shifts. reversed input costs n(n - 1) / 2 of each. the shifts are exactly the pairs out of order, so nearly sorted input stays cheap. */
#include "insertion_sort.h"

/* insertion_sort's order: -1, 0 or 1 as x goes before, ties with, or goes after y */
static int ascending(int x, int y, void *ctx) {
    (void)ctx; /* nothing to keep */
    return (x > y) - (x < y);
}

void insertion_sort(int *a, size_t n) {
    insertion_sort_by(a, n, ascending, NULL);
}

void insertion_sort_by(int *a, size_t n, int (*cmp)(int x, int y, void *ctx), void *ctx) {
    for (size_t i = 1; i < n; i++) {
        int x = a[i]; /* hold the next item. a[0..i) is sorted already */
        size_t j = i; /* the gap it left */
        /* a bigger item on the left shifts right, into the gap. > stops at an equal item, so x
           stays behind it: that's what keeps the sort stable. j > 0 is tested first, so a[j - 1]
           never reads before a[0] */
        while (j > 0 && cmp(a[j - 1], x, ctx) > 0) {
            a[j] = a[j - 1];
            j--;
        }
        a[j] = x; /* drop x into the gap */
    }
}
swift/algos/InsertionSort.swift
/// insertion sort, in place and stable. each pass holds the next item, shifts every bigger item one slot to the right, and drops the held item into the gap. sorted input costs n - 1 comparisons and no shifts. reversed input costs n(n - 1) / 2 of each. the shifts are exactly the pairs out of order, so nearly sorted input stays cheap.
public func insertionSort<T>(_ a: inout [T], by areInIncreasingOrder: (T, T) -> Bool) {
    for i in a.indices.dropFirst() { // 1 up to n - 1. 1..<a.count would trap on an empty array
        let x = a[i] // hold the next item. a[0..<i] is sorted already
        var j = i // the gap it left
        // a bigger item on the left shifts right, into the gap. only a strictly bigger one: an equal item stops the
        // pass, so x stays behind it, and that's what keeps the sort stable
        while j > 0 && areInIncreasingOrder(x, a[j - 1]) {
            a[j] = a[j - 1]
            j -= 1
        }
        a[j] = x // drop x into the gap
    }
}

/// sorts in ascending order
public func insertionSort<T: Comparable>(_ a: inout [T]) {
    insertionSort(&a, by: <)
}
python/algos/insertion_sort.py
"""insertion sort, in place and stable. each pass holds the next item, shifts every bigger item one slot to the right, and drops the held item into the gap. sorted input costs n - 1 comparisons and no shifts. reversed input costs n(n - 1) / 2 of each. the shifts are exactly the pairs out of order, so nearly sorted input stays cheap."""

from __future__ import annotations

from collections.abc import Callable
from typing import Any, TypeVar

T = TypeVar("T")


def insertion_sort(items: list[T], key: Callable[[T], Any] | None = None) -> None:
    """Sort items in place, smallest first, by key(item) if given. Equal items keep their original order."""
    k: Callable[[T], Any] = key or (lambda x: x)
    for i in range(1, len(items)):
        x = items[i]  # hold the next item. items[0:i] is sorted already
        kx = k(x)  # its key, worked out once per pass
        j = i  # the gap it left
        # a bigger item on the left shifts right, into the gap. > stops at an equal item, so x stays
        # behind it: that's what keeps the sort stable
        while j > 0 and k(items[j - 1]) > kx:
            items[j] = items[j - 1]
            j -= 1
        items[j] = x  # drop x into the gap

pitfalls

variants

practice

how real libraries do it

sources

  1. 38, 27, 43, 3, 9, 82, 10 is the array in the merge sort algorithm diagram (opens in a new tab) on wikimedia commons. the merge sort page added 19 to make eight, and this page uses the same eight so the two sorts can be compared on one input. ↩

  2. tim peters’ design notes, listsort.txt (opens in a new tab), in cpython 3.15.0, note BINSORT: a binary insertion sort is a textbook insertion sort that finds the slot with the equivalent of bisect.bisect_right, in logarithmic time. it stays quadratic, because a faster search doesn’t cut the data movement, but in cpython a comparison costs far more than moving a pointer, so cutting comparisons pays. ↩

  3. d. l. shell, a high-speed sorting procedure (opens in a new tab), communications of the acm, volume 2, issue 7, july 1959. ↩

  4. DualPivotQuicksort.java (opens in a new tab) at jdk-27-ga, which Arrays.sort(int[]) (opens in a new tab) calls: MAX_INSERTION_SORT_SIZE is 44 and MAX_MIXED_INSERTION_SORT_SIZE is 65. the sort loop (opens in a new tab) sends a small leftmost part to insertionSort and a small part elsewhere to mixedInsertionSort, whose comment (opens in a new tab) says the pivot from the left part is smaller than everything in the part, so it plays the role of a sentinel and the check of the left range is skipped. insertionSort (opens in a new tab) holds the item and shifts the bigger ones right. ↩ ↩2

  5. listobject.c (opens in a new tab) in cpython 3.15.0: the main loop finds the next natural run and, if it’s shorter than minrun, extends it with binarysort (opens in a new tab), a stable binary insertion sort in place. MAX_MINRUN is 64, and listsort.txt (opens in a new tab) says that when the list is shorter than that, minrun is the whole list, so binary insertion sort sorts all of it. ↩

  6. zsortordered.go (opens in a new tab) at go1.27.3: pdqsortOrdered has maxInsertion = 12, and a range that long or shorter goes to insertionSortOrdered (opens in a new tab), which swaps data[j] with data[j-1] while the left one is bigger. zsortanyfunc.go (opens in a new tab) has the same threshold for SortFunc, and its stableCmpFunc (opens in a new tab) sorts blocks of 20 by insertion sort before merging them. ↩

  7. rust 1.99.1. stable/mod.rs (opens in a new tab) and unstable/mod.rs (opens in a new tab): MAX_LEN_ALWAYS_INSERTION_SORT is 20, and the comment says the small binary size of insertion sort matters more than speed for a single sort call, because of the instruction cache. insert_tail (opens in a new tab) in smallsort.rs reads the tail item out, copies each bigger neighbor one slot right, and keeps a gap guard that writes the item back if a comparison panics. the general small sort (opens in a new tab) sorts the start of each half with a sorting network, extends each half with insert_tail, and merges the two. it only takes types that are Freeze, with no interior mutability: the rest get plain insertion sort (opens in a new tab) in sort, and the same fallback (opens in a new tab) in sort_unstable. ↩