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 , the unknown line costs , 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 , let be the number of times the while test on line 4 is evaluated during the iteration with that .
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 and once more when reaches and the loop ends: times.
- Lines 2, 3 and 7 run once per iteration: times.
- In iteration , the
whiletest runs times; the body runs once fewer, because the last test fails.
Adding cost times count over all lines gives the exact running time:
Everything here is fixed by except the , which depend on how the input is ordered. In iteration the body runs once for each element of the sorted prefix that is greater than the key, so is the number of prefix elements larger than .
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: for every , and the sums are and .
This has the form for constants and : a linear function of .
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 : the test is evaluated for and once more for , so . Using :
Substituting and collecting powers of :
This has the form : a quadratic function of . 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 with , because each inversion is undone by exactly one shift: equals the inversion count.
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:
#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 distinct values. In iteration the key is equally likely to be the smallest, second smallest, ..., largest of the first elements, so the number of prefix elements larger than it is uniform on , with mean . Therefore
exactly half the worst case. The running time is still a quadratic , with a leading coefficient half as large. The exhaustive table in Worst, Best and Average Case confirms for 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 next to its leading term alone.
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 the lower-order terms add 11 percent; at 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 comparisons on every input of size , 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 in iteration ?
- The value of the key
- The number of elements in the sorted prefix that are greater than the key
- The index where the key ends up
- Always
On a reversed array of distinct values, how many times does the while test of insertion sort run in total?
Why does the total number of shifts in insertion sort equal the number of inversions of the input?
- Because each shift swaps a pair of adjacent out-of-order elements, removing exactly one inversion, and the sorted array has none
- Because both are always
- Because shifts only happen on sorted input
- It is a coincidence for
In the made-up-constants example, the exact worst case is about 1.3 percent above at . What happens to that gap as grows?
- It stays at 1.3 percent
- It grows without bound
- It shrinks towards 0, because the lower-order terms grow more slowly than
- It becomes negative