How insertion sort charges one move per inversion

Short answer: Insertion sort grows a sorted prefix by sliding the next item left until it sits in order. Each slide removes one inversion, so the number of moves equals the inversion count. Sorted input is Θ(n). Reversed input is Θ(n²). The sort is stable and in place, and it is the base case hybrid sorts use on a short or nearly ordered slice.


What the problem actually asks

A permutation’s inversion count is the number of pairs standing in the wrong order. A sort that only swaps neighbors, or only slides an item one slot, will perform a move per inversion. Insertion sort makes that accounting exact, and it stops moving an item the moment the item reaches a key that is smaller or equal.

The prefix to the left of the item being inserted is already sorted. That is the invariant a reader uses to see why the scan can stop at the first key that is less than or equal to the new item.


What the algorithm guarantees

On an array, inserting item i into a prefix of length i costs as many slides as there are inversions that end at i. Summed over i, the slide count equals the inversion count. The best case is n−1 comparisons and no slide. The worst case is n(n−1)/2 comparisons and the same number of slides. Extra memory is the register that holds the item being inserted.

Equal keys stop the slide. The new item is placed to the right of equals already in the prefix, so the sort is stable. Binary search can locate the hole in O(log i) comparisons, and the subsequent slide still moves every intervening item. Binary insertion therefore saves comparisons and keeps the quadratic move bound.


The working steps

  1. The prefix a[0..0] is sorted.
  2. For i from 1 to n−1, copy a[i] into a register and set j to i.
  3. While j > 0 and a[j−1] is strictly greater than the register, copy a[j−1] one slot right and decrease j.
  4. Write the register into a[j]. The prefix a[0..i] is sorted, and equals stayed in their previous order.
  5. A binary search may replace the linear scan that finds j. The slide from i down to j remains.

This counts comparisons and adjacent moves in memory. It is the right base case under a few dozen items, and the wrong whole-array sort once the inversion count can be quadratic. A mergesort of long runs removes many inversions per move.


Approaches that look simpler and fail

Approach Why it fails when the inversion count may be quadratic
Using it as the only sort for a large random array A random permutation has Θ(n²) inversions. The algorithm performs one move for each of them.
Binary insertion, cited as an n log n sort The search becomes n log n comparisons. Sliding the hole still copies Θ(n²) items on a reversed array.
Swapping past equal keys The prefix invariant can be restored either way, and equals have changed order. Stability is gone.
Stopping the slide at a strictly smaller key only Stopping at a smaller key and continuing through equals is correct. Stopping at a smaller-or-equal key and then swapping with that equal key reorders equals.

The quadratic move bound is acceptable inside a hybrid, on slices below a few dozen items, where startups of a merge or a heap cost more than the slides. Timsort and introsort both do this.


A working example

The Bash script and the Python script insertion-sort the same integers. Each new key walks left through the inversions in front of it. Both print 1 2 2 3 4.

a=(4 2 2 3 1)
n=${#a[@]}
for ((i=1; i<n; i++)); do
  key=${a[i]}
  j=$((i-1))
  while (( j >= 0 && a[j] > key )); do
    a[j+1]=${a[j]}
    j=$((j-1))
  done
  a[j+1]=$key
done
echo "${a[*]}"
a = [4, 2, 2, 3, 1]
for i in range(1, len(a)):
    key = a[i]
    j = i - 1
    while j >= 0 and a[j] > key:
        a[j + 1] = a[j]
        j -= 1
    a[j + 1] = key
assert a == sorted(a)
print(*a)

Where it is used

Insertion sort is the base case of timsort and of introsort once the slice is shorter than a few dozen items. A nearly sorted array is its other real job, because each inversion costs one move. A long random array belongs to the n log n sort that calls it.


When you can drop this algorithm

Drop insertion sort as the top-level sort when n is large and the input may be random or reversed. Mergesort, heapsort, or a hybrid then provides the n log n envelope. Keep insertion sort for a short slice, for a list known to have few inversions, and as the stable in-place base case of a larger sort.


Why this stays published

We publish this so a search for insertion sort returns the inversion accounting, the stable stop at equal keys, and the reason binary search does not repair the move bound. Insertion sort performs one move per inversion, runs in linear time on sorted input, and stays quadratic whenever the inversion count is quadratic.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *