# insertion sort

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

source: https://learning.anthnydas.com/algos/insertion-sort/

## tl;dr

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

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](/algos/merge-sort/) page:[^diagram]

> **interactive figure:** 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.

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

hold the next item, 27. 38 is bigger, so it shifts right into the gap. the gap is at the front now, and 27 drops in. the first two are sorted.

hold 43. 38 isn't bigger, so nothing shifts: one comparison, and 43 drops back where it was.

hold 3. 43 is bigger and shifts. so is 38, so is 27. the gap reaches the front, and 3 drops in: 3 shifts, 3 comparisons.

hold 9. it slides past 43, 38 and 27 the same way, then meets 3, which isn't bigger, and stops: 3 shifts, and a fourth comparison to find the stop. 82 stays put.

10 and 19 each slide past the four bigger items and stop. sorted, after 15 shifts and 20 comparisons. merge sort made 17 comparisons on these eight, and 24 copies.

## 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.

> **interactive figure:** 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.

> **interactive figure:** 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

```text
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

> **interactive figure:** 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.

- **every shift undoes one pair out of order.** a shift moves a bigger item past the held one, and nothing else changes order. so the shifts a sort makes are exactly the pairs that start out in the wrong order, the inversions, no matter which pass undoes which. the eight numbers above have 15, and took 15 shifts
- **comparisons are the shifts, plus one per pass.** each shift costs a comparison, and each pass ends with one more: the comparison that finds an item that isn't bigger. the exception is an item smaller than everything before it. it shifts the whole sorted part, hits the front, and never makes that last comparison. on the eight numbers, 27 and 3 do that, so 15 + 7 - 2 = 20 comparisons
- **sorted input: n - 1 comparisons, no shifts.** every pass compares once and stops. a million sorted items take 999,999 comparisons
- **reversed input: n(n - 1) / 2 of each.** every pair is out of order, so every item shifts past everything before it. 1,024 items reversed take 523,776 shifts, and as many comparisons
- **nearly sorted input: about n + k.** k pairs out of order cost k shifts and about n comparisons. 1,024 items with 16 neighbors swapped take 1,039 comparisons and 16 shifts: the sorted price, plus the mess

## complexity

| input         | comparisons | shifts     |
| ------------- | ----------- | ---------- |
| sorted        | n - 1       | 0          |
| nearly sorted | about n + k | k          |
| random        | about n²/4  | about n²/4 |
| reversed      | n(n - 1)/2  | n(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.

> **interactive figure:** 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`

```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`

```rust
//! 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`

```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`

```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`

```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`

```python
"""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

- **swapping instead of shifting.** swapping the held item one slot at a time sorts fine, but writes two cells per step where a shift writes one. hold the item, shift the bigger ones, write it once at the end
- **`>=` instead of `>`.** an equal item shifts past the held one, and equal items swap places: not stable anymore
- **forgetting the wall.** without `j > 0`, the smallest item so far reads `a[-1]`: out of range, or in c, whatever sits in memory before the array
- **big random input.** about n²/4 comparisons: 273,132 for 1,024 items, and roughly four times more for every doubling. past a few dozen items, use merge sort, quicksort or heap sort, unless the input is nearly sorted
- **shifting a linked list.** there's nothing to shift. walk from the front to the right spot and relink: same comparisons, no moves

## variants

- **binary insertion sort.** find the slot with a [binary search](/algos/binary-search/) over the sorted part, then shift. the comparisons drop to O(n log n), but the shifts don't, so it's still O(n²). it pays when a comparison costs far more than a move, which is why python's sort uses it[^binsort]
- **shell sort.** insertion sort on the items h apart, for a shrinking list of gaps h that ends at 1. the early passes carry items a long way in one shift, and the last pass finds the array nearly sorted. donald shell, 1959[^shell]
- **with a sentinel.** put the smallest item at the front first, and the inner loop can drop the `j > 0` check: it stops on the sentinel. java's sort gets the same effect from a pivot that's already to the left[^java]
- **on a linked list.** no shifting: walk to the spot and relink. the same O(n²) comparisons, and no moves at all
- **inside faster sorts.** the small pieces at the bottom of a quicksort or merge sort go to insertion sort. how small is below

## practice

- [insertion sort list](https://leetcode.com/problems/insertion-sort-list/): the algorithm on a linked list. walk to the spot and relink
- [insert interval](https://leetcode.com/problems/insert-interval/): one pass of it on a sorted list of intervals, then merge the overlaps
- [sort the people](https://leetcode.com/problems/sort-the-people/): pairs sorted by one key. a thousand items at most, so insertion sort is fine
- [relative sort array](https://leetcode.com/problems/relative-sort-array/): a stable sort by a custom order. stability does the work
- [global and local inversions](https://leetcode.com/problems/global-and-local-inversions/): the inversions are the shifts. when is every one a single step?
- [count of smaller numbers after self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/): each item's slot in the sorted list of the items after it is its answer. binary insertion from the back finds the slot in log n comparisons, and the shifts are the part to speed up

## how real libraries do it

- **python.** `list.sort` is timsort: it finds natural runs and merges them. a run shorter than minrun is extended with binary insertion sort first, and minrun tops out at 64, so a list under 64 items is sorted by binary insertion sort alone[^cpython]
- **go.** `slices.Sort` and `slices.SortFunc` are pdqsort, and hand any range of 12 or fewer items to insertion sort. its inner loop swaps neighbors instead of shifting. `slices.SortStableFunc` starts with insertion sort on blocks of 20, then merges them[^go]
- **rust.** `sort` and `sort_unstable` both sort a slice of up to 20 items with insertion sort alone, to keep the code small. inside the main sorts, the small-sort step sorts the start of each half with a sorting network, then insertion sort extends each half: it holds the next item and shifts the bigger ones right, with a guard that puts the item back if a comparison panics. a type with interior mutability, like `Cell`, skips the network and gets insertion sort alone[^rust]
- **java.** `Arrays.sort` on ints is dual-pivot quicksort. a leftmost part under 44 items goes to plain insertion sort, and other small parts to a mixed insertion sort that skips the front check, because the pivot to its left is a sentinel[^java]

[^diagram]: 38, 27, 43, 3, 9, 82, 10 is the array in the [merge sort algorithm diagram](https://commons.wikimedia.org/wiki/File:Merge_sort_algorithm_diagram.svg) 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.

[^binsort]: tim peters' design notes, [listsort.txt](https://github.com/python/cpython/blob/v3.15.0/Objects/listsort.txt#L816-L838), 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.

[^shell]: d. l. shell, [a high-speed sorting procedure](https://doi.org/10.1145/368370.368387), communications of the acm, volume 2, issue 7, july 1959.

[^cpython]: [listobject.c](https://github.com/python/cpython/blob/v3.15.0/Objects/listobject.c#L3119-L3137) in cpython 3.15.0: the main loop finds the next natural run and, if it's shorter than minrun, extends it with [`binarysort`](https://github.com/python/cpython/blob/v3.15.0/Objects/listobject.c#L1801-L1813), a stable binary insertion sort in place. `MAX_MINRUN` is 64, and [listsort.txt](https://github.com/python/cpython/blob/v3.15.0/Objects/listsort.txt#L273-L275) says that when the list is shorter than that, minrun is the whole list, so binary insertion sort sorts all of it.

[^go]: [zsortordered.go](https://github.com/golang/go/blob/go1.27.3/src/slices/zsortordered.go#L63-L77) at go1.27.3: `pdqsortOrdered` has `maxInsertion = 12`, and a range that long or shorter goes to [`insertionSortOrdered`](https://github.com/golang/go/blob/go1.27.3/src/slices/zsortordered.go#L11-L18), which swaps `data[j]` with `data[j-1]` while the left one is bigger. [zsortanyfunc.go](https://github.com/golang/go/blob/go1.27.3/src/slices/zsortanyfunc.go#L61-L75) has the same threshold for `SortFunc`, and its [`stableCmpFunc`](https://github.com/golang/go/blob/go1.27.3/src/slices/zsortanyfunc.go#L335-L343) sorts blocks of 20 by insertion sort before merging them.

[^rust]: rust 1.99.1. [stable/mod.rs](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/stable/mod.rs#L71-L81) and [unstable/mod.rs](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/unstable/mod.rs#L43-L53): `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`](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/shared/smallsort.rs#L532-L571) 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](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/shared/smallsort.rs#L220-L277) 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](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/shared/smallsort.rs#L30-L47) in `sort`, and [the same fallback](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/shared/smallsort.rs#L75-L88) in `sort_unstable`.

[^java]: [DualPivotQuicksort.java](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/DualPivotQuicksort.java#L61-L69) at jdk-27-ga, which [`Arrays.sort(int[])`](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/Arrays.java#L98-L100) calls: `MAX_INSERTION_SORT_SIZE` is 44 and `MAX_MIXED_INSERTION_SORT_SIZE` is 65. [the sort loop](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/DualPivotQuicksort.java#L253-L270) sends a small leftmost part to `insertionSort` and a small part elsewhere to `mixedInsertionSort`, whose [comment](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/DualPivotQuicksort.java#L557-L566) 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`](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/DualPivotQuicksort.java#L687-L699) holds the item and shifts the bigger ones right.

## related

- https://learning.anthnydas.com/algos/merge-sort.md
- https://learning.anthnydas.com/algos/quicksort.md
- https://learning.anthnydas.com/algos/heap-sort.md
- https://learning.anthnydas.com/algos/big-o.md
- https://learning.anthnydas.com/algos/binary-search.md
- https://learning.anthnydas.com/ds/dynamic-array.md
