TExcelTAD
Home › Foundations of Algorithm Analysis › Counting Steps Exactly: The Cost of Insertion Sort

Counting Steps Exactly: The Cost of Insertion Sort

The RAM model says each pseudocode line costs some constant each time it runs. This lesson takes that literally and derives the exact running time of insertion sort as a formula in nn, the unknown line costs c1,…,c7c_1, \ldots, c_7, and one quantity that depends on the input. From the formula, the best, worst and average cases fall out with a little algebra, and a program that counts line executions confirms every one of them.

Exact counting is more work than the asymptotic shortcuts of the next sections. It is worth doing carefully once, because it shows precisely what those shortcuts throw away and why that is safe.

The cost table

Here is insertion sort again, as in Loop Invariants, with a cost and an execution count for each line. For i=1,…,n−1i = 1, \ldots, n - 1, let tit_i be the number of times the while test on line 4 is evaluated during the iteration with that ii.

text
INSERTION-SORT(a)                                cost   times
1  for i = 1 to n - 1                            c1     n
2      key = a[i]                                c2     n - 1
3      j = i - 1                                 c3     n - 1
4      while j >= 0 and a[j] > key               c4     sum of t_i
5          a[j + 1] = a[j]                       c5     sum of (t_i - 1)
6          j = j - 1                             c6     sum of (t_i - 1)
7      a[j + 1] = key                            c7     n - 1
  • Line 1's loop test runs once for each i=1,…,n−1i = 1, \ldots, n - 1 and once more when ii reaches nn and the loop ends: nn times.
  • Lines 2, 3 and 7 run once per iteration: n−1n - 1 times.
  • In iteration ii, the while test runs tit_i times; the body runs once fewer, because the last test fails.

Adding cost times count over all lines gives the exact running time:

T(n)=c1n+(c2+c3+c7)(n−1)+c4∑i=1n−1ti+(c5+c6)∑i=1n−1(ti−1).T(n) = c_1 n + (c_2 + c_3 + c_7)(n - 1) + c_4 \sum_{i=1}^{n-1} t_i + (c_5 + c_6) \sum_{i=1}^{n-1} (t_i - 1).

Everything here is fixed by nn except the tit_i, which depend on how the input is ordered. In iteration ii the body runs once for each element of the sorted prefix that is greater than the key, so ti−1t_i - 1 is the number of prefix elements larger than a[i]a[i].

The best case: a sorted array

If the array is already sorted, every key is at least as large as the element just before it, so the while test fails at once: ti=1t_i = 1 for every ii, and the sums are n−1n - 1 and 00.

T(n)=c1n+(c2+c3+c4+c7)(n−1)=(c1+c2+c3+c4+c7) n−(c2+c3+c4+c7).T(n) = c_1 n + (c_2 + c_3 + c_4 + c_7)(n - 1) = (c_1 + c_2 + c_3 + c_4 + c_7)\,n - (c_2 + c_3 + c_4 + c_7).

This has the form an+ban + b for constants aa and bb: a linear function of nn.

The worst case: a reversed array

If the array is in decreasing order, every key is smaller than every element of the prefix. The loop runs until j=−1j = -1: the test is evaluated for j=i−1,i−2,…,0j = i - 1, i - 2, \ldots, 0 and once more for j=−1j = -1, so ti=i+1t_i = i + 1. Using ∑i=1n−1i=n(n−1)2\sum_{i=1}^{n-1} i = \frac{n(n-1)}{2}:

∑i=1n−1ti=∑i=1n−1(i+1)=n(n−1)2+(n−1)=(n−1)(n+2)2,∑i=1n−1(ti−1)=∑i=1n−1i=n(n−1)2.\begin{aligned} \sum_{i=1}^{n-1} t_i &= \sum_{i=1}^{n-1} (i + 1) = \frac{n(n-1)}{2} + (n - 1) = \frac{(n-1)(n+2)}{2}, \\ \sum_{i=1}^{n-1} (t_i - 1) &= \sum_{i=1}^{n-1} i = \frac{n(n-1)}{2}. \end{aligned}

Substituting and collecting powers of nn:

T(n)=(c42+c5+c62)n2+(c1+c2+c3+c42−c5+c62+c7)n−(c2+c3+c4+c7).T(n) = \left(\frac{c_4}{2} + \frac{c_5 + c_6}{2}\right) n^2 + \left(c_1 + c_2 + c_3 + \frac{c_4}{2} - \frac{c_5 + c_6}{2} + c_7\right) n - (c_2 + c_3 + c_4 + c_7).

This has the form an2+bn+can^2 + bn + c: a quadratic function of nn. The exact coefficients are messy and machine-dependent, but the shape is not.

Checking the counts by running the code

The program below instruments each line with a counter and compares the counts with the formulas for sorted, reversed and random inputs. For random input the prediction uses the number of inversions, pairs of positions p<qp < q with a[p]>a[q]a[p] > a[q], because each inversion is undone by exactly one shift: ∑(ti−1)\sum (t_i - 1) equals the inversion count.

python · try it yourself
import random
from collections import Counter

def insertion_sort_counts(a):
    a, runs = list(a), Counter()
    i = 1
    while True:
        runs[1] += 1
        if i > len(a) - 1:
            break
        runs[2] += 1; key = a[i]
        runs[3] += 1; j = i - 1
        while True:
            runs[4] += 1
            if not (j >= 0 and a[j] > key):
                break
            runs[5] += 1; a[j + 1] = a[j]
            runs[6] += 1; j = j - 1
        runs[7] += 1; a[j + 1] = key
        i += 1
    return runs

def inversions(a):
    return sum(a[p] > a[q] for p in range(len(a)) for q in range(p + 1, len(a)))

n = 10
rng = random.Random(7)
inputs = {"sorted": list(range(n)), "reversed": list(range(n, 0, -1)),
          "random": rng.sample(range(100), n)}
for name, a in inputs.items():
    r = insertion_sort_counts(a)
    print(f"{name:>8}: " + "  ".join(f"L{k}={r[k]}" for k in range(1, 8)))
print()
inv = inversions(inputs["random"])
print(f"formulas, n = {n}: line 1 = n = {n}, lines 2, 3, 7 = n - 1 = {n - 1}")
print(f"  sorted:   line 4 = n - 1 = {n - 1}, lines 5, 6 = 0")
print(f"  reversed: line 4 = (n-1)(n+2)/2 = {(n - 1) * (n + 2) // 2}, lines 5, 6 = n(n-1)/2 = {n * (n - 1) // 2}")
print(f"  random:   inversions = {inv}, so line 4 = (n - 1) + {inv} = {n - 1 + inv}")
  sorted: L1=10  L2=9  L3=9  L4=9  L5=0  L6=0  L7=9
reversed: L1=10  L2=9  L3=9  L4=54  L5=45  L6=45  L7=9
  random: L1=10  L2=9  L3=9  L4=28  L5=19  L6=19  L7=9

formulas, n = 10: line 1 = n = 10, lines 2, 3, 7 = n - 1 = 9
  sorted:   line 4 = n - 1 = 9, lines 5, 6 = 0
  reversed: line 4 = (n-1)(n+2)/2 = 54, lines 5, 6 = n(n-1)/2 = 45
  random:   inversions = 19, so line 4 = (n - 1) + 19 = 28

In C++

The same instrumented sort in C++. The random input is written out: it is the list that rng.sample drew in the Python version, so every count is identical:

cpp · try it yourself
#include <array>
#include <cstdio>
#include <vector>
using namespace std;

// runs[k] = how many times pseudocode line k executed (index 0 unused)
array<long, 8> insertion_sort_counts(vector<int> a) {
    array<long, 8> runs{};
    int n = (int)a.size();
    int i = 1;
    while (true) {
        runs[1]++;
        if (i > n - 1) break;
        runs[2]++; int key = a[i];
        runs[3]++; int j = i - 1;
        while (true) {
            runs[4]++;
            if (!(j >= 0 && a[j] > key)) break;
            runs[5]++; a[j + 1] = a[j];
            runs[6]++; j = j - 1;
        }
        runs[7]++; a[j + 1] = key;
        i++;
    }
    return runs;
}

int inversions(const vector<int>& a) {
    int count = 0;
    for (size_t p = 0; p < a.size(); p++)
        for (size_t q = p + 1; q < a.size(); q++)
            if (a[p] > a[q]) count++;
    return count;
}

int main() {
    const int n = 10;
    vector<int> sorted_in, reversed_in;
    for (int v = 0; v < n; v++) sorted_in.push_back(v);
    for (int v = n; v > 0; v--) reversed_in.push_back(v);
    // the list that random.Random(7).sample(range(100), 10) drew in the Python version
    vector<int> random_in = {41, 19, 50, 83, 6, 9, 68, 12, 46, 74};
    struct Case { const char* name; vector<int> a; };
    for (const Case& c : {Case{"sorted", sorted_in}, Case{"reversed", reversed_in},
                          Case{"random", random_in}}) {
        array<long, 8> r = insertion_sort_counts(c.a);
        printf("%8s: ", c.name);
        for (int k = 1; k <= 7; k++) printf("L%d=%ld%s", k, r[k], k < 7 ? "  " : "\n");
    }
    printf("\n");
    int inv = inversions(random_in);
    printf("formulas, n = %d: line 1 = n = %d, lines 2, 3, 7 = n - 1 = %d\n", n, n, n - 1);
    printf("  sorted:   line 4 = n - 1 = %d, lines 5, 6 = 0\n", n - 1);
    printf("  reversed: line 4 = (n-1)(n+2)/2 = %d, lines 5, 6 = n(n-1)/2 = %d\n",
           (n - 1) * (n + 2) / 2, n * (n - 1) / 2);
    printf("  random:   inversions = %d, so line 4 = (n - 1) + %d = %d\n", inv, inv, n - 1 + inv);
}
  sorted: L1=10  L2=9  L3=9  L4=9  L5=0  L6=0  L7=9
reversed: L1=10  L2=9  L3=9  L4=54  L5=45  L6=45  L7=9
  random: L1=10  L2=9  L3=9  L4=28  L5=19  L6=19  L7=9

formulas, n = 10: line 1 = n = 10, lines 2, 3, 7 = n - 1 = 9
  sorted:   line 4 = n - 1 = 9, lines 5, 6 = 0
  reversed: line 4 = (n-1)(n+2)/2 = 54, lines 5, 6 = n(n-1)/2 = 45
  random:   inversions = 19, so line 4 = (n - 1) + 19 = 28

Every count matches its formula exactly.

The average case

For the average, assume the input is a uniformly random permutation of nn distinct values. In iteration ii the key is equally likely to be the smallest, second smallest, ..., largest of the first i+1i + 1 elements, so the number of prefix elements larger than it is uniform on {0,1,…,i}\{0, 1, \ldots, i\}, with mean i/2i/2. Therefore

E[∑i=1n−1(ti−1)]=∑i=1n−1i2=n(n−1)4,\mathrm{E}\left[\sum_{i=1}^{n-1} (t_i - 1)\right] = \sum_{i=1}^{n-1} \frac{i}{2} = \frac{n(n-1)}{4},

exactly half the worst case. The running time is still a quadratic a′n2+b′n+c′a'n^2 + b'n + c', with a leading coefficient half as large. The exhaustive table in Worst, Best and Average Case confirms n(n−1)/4n(n-1)/4 for nn up to 7.

Plugging in made-up constants

To see how much the lower-order terms matter, give the constants concrete values. Suppose, purely for illustration, that lines 1 to 7 cost 2, 3, 1, 5, 6, 1 and 3 units. The program prints the exact worst-case T(n)T(n) next to its leading term alone.

python · try it yourself
c = {1: 2, 2: 3, 3: 1, 4: 5, 5: 6, 6: 1, 7: 3}

def worst(n):
    s_t = (n - 1) * (n + 2) // 2
    s_body = n * (n - 1) // 2
    return c[1] * n + (c[2] + c[3] + c[7]) * (n - 1) + c[4] * s_t + (c[5] + c[6]) * s_body

lead = (c[4] + c[5] + c[6]) / 2          # coefficient of n^2
print(f"leading term: {lead} n^2")
for n in [10, 100, 1000, 10000]:
    print(f"n = {n:>6}: T(n) = {worst(n):>12,}   {lead:g} n^2 = {lead * n * n:>14,.0f}   ratio {worst(n) / (lead * n * n):.4f}")
leading term: 6.0 n^2
n =     10: T(n) =          668   6 n^2 =            600   ratio 1.1133
n =    100: T(n) =       60,788   6 n^2 =         60,000   ratio 1.0131
n =   1000: T(n) =    6,007,988   6 n^2 =      6,000,000   ratio 1.0013
n =  10000: T(n) =  600,079,988   6 n^2 =    600,000,000   ratio 1.0001

At n=10n = 10 the lower-order terms add 11 percent; at n=10 000n = 10\,000 they add 0.01 percent. For large inputs the leading term is the running time, to within rounding. That observation is the whole motivation for the Order of Growth lesson that follows.

When all cases agree

Not every algorithm has a gap between its best and worst case. Selection sort always scans the entire unsorted suffix to find its minimum, so it makes exactly n(n−1)2\frac{n(n-1)}{2} comparisons on every input of size nn, sorted or not. Its best, worst and average cases are the same quadratic. Insertion sort is adaptive: its cost reflects how much disorder the input contains. That is why it is the method of choice for small or nearly sorted arrays, and why fast library sorts switch to it for short runs.

Test yourself

In insertion sort, what is ti−1t_i - 1 in iteration ii?

  1. The value of the key
  2. The number of elements in the sorted prefix that are greater than the key
  3. The index where the key ends up
  4. Always ii

On a reversed array of nn distinct values, how many times does the while test of insertion sort run in total?

  1. n−1n - 1
  2. n(n−1)2\frac{n(n-1)}{2}
  3. (n−1)(n+2)2\frac{(n-1)(n+2)}{2}
  4. n2n^2

Why does the total number of shifts in insertion sort equal the number of inversions of the input?

  1. Because each shift swaps a pair of adjacent out-of-order elements, removing exactly one inversion, and the sorted array has none
  2. Because both are always n(n−1)/2n(n-1)/2
  3. Because shifts only happen on sorted input
  4. It is a coincidence for n=10n = 10

In the made-up-constants example, the exact worst case is about 1.3 percent above 6n26n^2 at n=100n = 100. What happens to that gap as nn grows?

  1. It stays at 1.3 percent
  2. It grows without bound
  3. It shrinks towards 0, because the lower-order terms grow more slowly than n2n^2
  4. It becomes negative