Cs · Computer Science

Insertion Sort Average Case – Comparisons, Shifts and Θ(n²)

Published By the 9to5Science editorial team

At a glance

  1. 1. Count shifts as inversions

    Each shift fixes exactly one inverted pair.

  2. 2. Average the inversions

    Each pair is inverted with probability ½, giving n(n − 1)/4 shifts.

  3. 3. Add the comparisons

    Each insertion costs about one comparison more than its shifts.

  4. 4. Conclude the growth

    About n²/4 operations on average, which is Θ(n²) and half the worst case.

Insertion sort builds a sorted prefix one element at a time. Element ii is compared with the elements to its left, scanning right to left, and the larger ones are shifted one place to the right until the right spot is found:

def insertion_sort(a):
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0 and a[j] > key:   # one comparison per loop test with j >= 0
            a[j + 1] = a[j]            # one shift
            j -= 1
        a[j + 1] = key

“Average case” means the expected cost when the input is a uniformly random permutation of nn distinct keys.

Shifts: count the inversions

An inversion is a pair (i,j)(i, j) with i<ji < j but ai>aja_i > a_j. Each shift fixes exactly one inversion and creates no new ones, so

shifts=number of inversions.\text{shifts} = \text{number of inversions}.

Each of the (n2)\binom{n}{2} pairs is inverted with probability 12\tfrac12 in a random permutation. By linearity of expectation,

E[shifts]=12(n2)=n(n−1)4.\mathbb{E}[\text{shifts}] = \frac12 \binom{n}{2} = \frac{n(n-1)}{4}.

Comparisons: exact expectation

When the element at position ii (counting from 1) is inserted, the sorted prefix has i−1i - 1 elements, and the new key’s rank among the first ii is uniform. Say it moves past kk larger elements, where k∈{0,1,…,i−1}k \in \{0, 1, \dots, i-1\}, each with probability 1/i1/i.

  • If k<i−1k < i - 1, the loop makes kk successful comparisons plus one failing one: k+1k + 1 comparisons.
  • If k=i−1k = i - 1 (the key is the new minimum), the loop stops because jj reaches −1-1, after i−1i - 1 comparisons.

So the expected number of comparisons for this insertion is

1i(∑k=0i−2(k+1)+(i−1))=i−12+i−1i=i+12−1i.\frac1i\left(\sum_{k=0}^{i-2} (k+1) + (i-1)\right) = \frac{i-1}{2} + \frac{i-1}{i} = \frac{i+1}{2} - \frac1i.

Summing over i=2,…,ni = 2, \dots, n:

E[comparisons]=∑i=2n(i+12−1i)=n2+3n4−Hn,\mathbb{E}[\text{comparisons}] = \sum_{i=2}^{n}\left(\frac{i+1}{2} - \frac1i\right) = \frac{n^2 + 3n}{4} - H_n,

where Hn=1+12+⋯+1n≈ln⁡nH_n = 1 + \tfrac12 + \dots + \tfrac1n \approx \ln n. Equivalently, this is n(n−1)4+n−Hn\dfrac{n(n-1)}{4} + n - H_n: one comparison per inversion, plus about one extra comparison per insertion.

Check, n=3n = 3: the formula gives 184−116=83≈2.67\tfrac{18}{4} - \tfrac{11}{6} = \tfrac{8}{3} \approx 2.67. By hand, the second element always costs 1 comparison, and the third costs 42−13=53\tfrac{4}{2} - \tfrac13 = \tfrac53 on average, for a total of 83\tfrac83.

Best, average and worst case

CaseInputComparisonsShifts
Bestalready sortedn−1n - 100
Averagerandom permutationn2+3n4−Hn∼n24\frac{n^2+3n}{4} - H_n \sim \frac{n^2}{4}n(n−1)4\frac{n(n-1)}{4}
Worstreverse sortedn(n−1)2\frac{n(n-1)}{2}n(n−1)2\frac{n(n-1)}{2}

So the average case is Θ(n2)\Theta(n^2), with a constant about half that of the worst case.

Why insertion sort is still used

  • On nearly sorted data its running time is Θ(n+I)\Theta(n + I), where II is the number of inversions, which can be close to linear.
  • It is stable, in place, and has very low overhead. Hybrid sorts such as Timsort and introsort switch to insertion sort for small subarrays (typically 16 to 64 elements).
  • Binary insertion sort cuts comparisons to O(nlog⁡n)O(n \log n), but the shifts remain Θ(n2)\Theta(n^2) on average.

Common mistakes

  • Saying the average case is "n2/2n^2/2". That is the worst case. The average is half of that.
  • Equating comparisons and shifts. They differ by about n−Hnn - H_n, which matters for small nn.
  • Assuming duplicates don’t matter. The analysis above assumes distinct keys. With many equal keys there are fewer inversions.

References

  1. Knuth, D. E. (1998). The Art of Computer Programming, Vol. 3 – Sorting and Searching (2nd ed.), Section 5.2.1. Addison-Wesley.
  2. Cormen, T. H. et al. (2022). Introduction to Algorithms (4th ed.), Section 2.2. MIT Press.

Spotted an error? Send a correction. Read how we write and check articles in our editorial policy.