TExcelTAD
Home › Foundations of Algorithm Analysis › Worst, Best and Average Case

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 nn" 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 nn, and let T(x)T(x) be the number of steps it takes on instance xx. Let In\mathcal{I}_n be the set of instances of size nn.

  • Worst case: Tworst(n)=max⁡x∈InT(x)T_{\text{worst}}(n) = \max_{x \in \mathcal{I}_n} T(x), the most work on any input of size nn.
  • Best case: Tbest(n)=min⁡x∈InT(x)T_{\text{best}}(n) = \min_{x \in \mathcal{I}_n} T(x), the least work.
  • Average case: Tavg(n)=E[T(X)]T_{\text{avg}}(n) = \mathrm{E}[T(X)], the expected work when the input XX is drawn from some probability distribution over In\mathcal{I}_n.

The average case is only meaningful together with its distribution. For sorting, the usual assumption is that all n!n! orderings of nn distinct values are equally likely. For searching, one might assume the target is equally likely to be at any position.

Always: Tbest(n)≤Tavg(n)≤Tworst(n)T_{\text{best}}(n) \le T_{\text{avg}}(n) \le T_{\text{worst}}(n), because an average lies between the minimum and the maximum.

Linear search, worked out

Search an array of nn distinct values for xx, comparing from left to right.

  • Best case: xx is at position 0: 1 comparison.
  • Worst case: xx is at the last position or absent: nn comparisons.
  • Average case, xx present at a uniformly random position: position kk costs k+1k + 1 comparisons, so
E[T]=∑k=0n−11n(k+1)=1n⋅n(n+1)2=n+12.\mathrm{E}[T] = \sum_{k=0}^{n-1} \frac{1}{n}(k + 1) = \frac{1}{n} \cdot \frac{n(n+1)}{2} = \frac{n + 1}{2}.

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 nn 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.

python · try it yourself
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:

cpp · try it yourself
#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 n(n−1)/2n(n-1)/2, and the average over all permutations is exactly n(n−1)/4n(n-1)/4: 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:

  1. 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.
  2. 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.
  3. The average is often no better in order of growth. Insertion sort's average is n(n−1)/4n(n-1)/4, 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 n=200n = 200 (100 pairs) the expected number of shifts is 100⋅12=50100 \cdot \frac{1}{2} = 50.

python · try it yourself
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 nn makes how many comparisons on average?

  1. 11
  2. n4\frac{n}{4}
  3. n+12\frac{n+1}{2}
  4. nn

For insertion sort on nn distinct values, which instance is the worst case?

  1. The sorted array
  2. The reverse-sorted array
  3. An array with the largest value first and the rest sorted
  4. Every instance costs the same

Why is the best-case running time rarely used to judge an algorithm?

  1. It is always zero
  2. It is hard to compute
  3. Almost any algorithm can be given a fast best case by special-casing one easy input, so it says little about quality
  4. It is always equal to the worst case

What does an average-case running time depend on, besides the algorithm and nn?

  1. Nothing else
  2. The probability distribution assumed over the inputs
  3. The programming language
  4. The worst case