Worst, Best and Average Case
Most algorithms do different amounts of work on different inputs of the same size. Insertion sort barely moves anything when the array is already sorted, and moves almost everything when it is in reverse order. So "the running time on inputs of size " is not one number but a whole collection of numbers, one per instance. This lesson defines the three standard ways of summarising that collection and explains why algorithm designers usually pick the pessimistic one.
Three summaries
Fix an algorithm and a size , and let be the number of steps it takes on instance . Let be the set of instances of size .
- Worst case: , the most work on any input of size .
- Best case: , the least work.
- Average case: , the expected work when the input is drawn from some probability distribution over .
The average case is only meaningful together with its distribution. For sorting, the usual assumption is that all orderings of distinct values are equally likely. For searching, one might assume the target is equally likely to be at any position.
Always: , because an average lies between the minimum and the maximum.
Linear search, worked out
Search an array of distinct values for , comparing from left to right.
- Best case: is at position 0: 1 comparison.
- Worst case: is at the last position or absent: comparisons.
- Average case, present at a uniformly random position: position costs comparisons, so
The average is about half the worst case: the same order of growth, a smaller constant. That is typical, and it is one reason the worst case is a good summary.
Insertion sort over every input
For small you can compute all three summaries exactly by running the algorithm on every permutation. The program counts shifts, the executions of a[j + 1] = a[j], which is the work that varies between inputs.
from itertools import permutations
from fractions import Fraction
def shifts(a):
a, count = list(a), 0
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
count += 1
a[j + 1] = key
return count
print(" n best worst average n(n-1)/4")
for n in range(1, 8):
counts = [shifts(p) for p in permutations(range(n))]
avg = Fraction(sum(counts), len(counts))
print(f"{n:>2} {min(counts):>6} {max(counts):>6} {str(avg):>8} {str(Fraction(n * (n - 1), 4)):>10}") n best worst average n(n-1)/4
1 0 0 0 0
2 0 1 1/2 1/2
3 0 3 3/2 3/2
4 0 6 3 3
5 0 10 5 5
6 0 15 15/2 15/2
7 0 21 21/2 21/2
In C++
In C++, std::next_permutation walks through every permutation, and a small helper prints the averages as reduced fractions:
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
long shifts(vector<int> a) {
long count = 0;
for (int i = 1; i < (int)a.size(); i++) {
int key = a[i], j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
count++;
}
a[j + 1] = key;
}
return count;
}
// p/q in lowest terms, printed like Python's Fraction
string fraction(long p, long q) {
long g = gcd(p, q);
p /= g; q /= g;
return q == 1 ? to_string(p) : to_string(p) + "/" + to_string(q);
}
int main() {
printf(" n best worst average n(n-1)/4\n");
for (int n = 1; n < 8; n++) {
vector<int> p(n);
iota(p.begin(), p.end(), 0); // 0, 1, ..., n-1: the first permutation
long best = -1, worst = 0, total = 0, count = 0;
do {
long s = shifts(p);
best = best < 0 ? s : min(best, s);
worst = max(worst, s);
total += s;
count++;
} while (next_permutation(p.begin(), p.end()));
printf("%2d %6ld %6ld %8s %10s\n", n, best, worst,
fraction(total, count).c_str(), fraction(n * (n - 1), 4).c_str());
}
} n best worst average n(n-1)/4
1 0 0 0 0
2 0 1 1/2 1/2
3 0 3 3/2 3/2
4 0 6 3 3
5 0 10 5 5
6 0 15 15/2 15/2
7 0 21 21/2 21/2
The best case (sorted input) needs no shifts, the worst case (reversed input) needs , and the average over all permutations is exactly : half the worst case again. The Counting Steps Exactly lesson derives these formulas; the Indicator Random Variables lesson proves the average with a two-line argument.
Watch the worst case in action: on a reversed array every key travels all the way to the front.
Why the worst case is the default
Analyses in this track state worst-case bounds unless they say otherwise. Three reasons:
- It is a guarantee. A worst-case bound holds for every input, including the ones an adversary or an unlucky day sends you. A web server that is fast "on average" but quadratic on one crafted request can be taken down by that request.
- The worst case happens often. Searching for a value that is not present is the worst case of linear search, and in many applications most searches fail.
- The average is often no better in order of growth. Insertion sort's average is , still quadratic. When the average and the worst case grow at the same rate, the simpler worst-case analysis says everything you need.
The best case, by contrast, is rarely informative. Any algorithm can be given a fast best case by first checking for one easy instance ("if the array is already sorted, return it"), which says nothing about its quality.
When the average depends on the distribution
The uniform distribution is a modelling choice, and real inputs often do not follow it. Data that arrives nearly sorted, such as log entries with slightly out-of-order timestamps, is far kinder to insertion sort than random data. The program below compares random permutations with nearly sorted ones made by swapping each neighbouring pair (positions 0 and 1, 2 and 3, and so on) with probability 1/2, so every element is at most one place from where it belongs. Each swapped pair costs one shift, so for (100 pairs) the expected number of shifts is .
import random
def shifts(a):
a, count = list(a), 0
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
count += 1
a[j + 1] = key
return count
def nearly_sorted(n, rng):
a = list(range(n))
for i in range(0, n - 1, 2): # swap some neighbouring pairs
if rng.random() < 0.5:
a[i], a[i + 1] = a[i + 1], a[i]
return a
rng = random.Random(7)
n, trials = 200, 100
uniform = sum(shifts(rng.sample(range(n), n)) for _ in range(trials)) / trials
nearly = sum(shifts(nearly_sorted(n, rng)) for _ in range(trials)) / trials
print(f"n = {n}: worst case {n * (n - 1) // 2} shifts")
print(f" random permutations: {uniform:.1f} on average (formula {n * (n - 1) / 4})")
print(f" nearly sorted input: {nearly:.1f} on average")n = 200: worst case 19900 shifts
random permutations: 9909.9 on average (formula 9950.0)
nearly sorted input: 48.8 on average
Under the nearly sorted distribution insertion sort is linear, not quadratic. Both statements are correct; they answer different questions. This is also why library sorts such as Python's Timsort are designed to exploit existing order. An average-case claim is only as trustworthy as its assumption about the inputs.
Randomization changes the question
There is a way to get average-case behaviour without trusting the input distribution: make the algorithm random. If an algorithm shuffles its input first, or picks random pivots, then its expected running time is an average over its own coin flips and holds for every input. That expected running time of a randomized algorithm is a different, stronger notion than the average case of a deterministic one, and the Hiring Problem lesson develops it.
Test yourself
Linear search for a value present at a uniformly random position among makes how many comparisons on average?
For insertion sort on distinct values, which instance is the worst case?
- The sorted array
- The reverse-sorted array
- An array with the largest value first and the rest sorted
- Every instance costs the same
Why is the best-case running time rarely used to judge an algorithm?
- It is always zero
- It is hard to compute
- Almost any algorithm can be given a fast best case by special-casing one easy input, so it says little about quality
- It is always equal to the worst case
What does an average-case running time depend on, besides the algorithm and ?
- Nothing else
- The probability distribution assumed over the inputs
- The programming language
- The worst case