Worst-Case, Average-Case, and Best-Case Analysis
Three Kinds of Analysis
For an input size , define the cost function for a specific input instance :
- Worst-case: — the maximum cost over all inputs of size .
- Best-case: — the minimum cost over all inputs of size .
- Average-case: — the expected cost, assuming some probability distribution over inputs.
Insertion Sort as Canonical Example
Recall the cost expression for Insertion Sort:
where is the number of WHILE-loop iterations for iteration . The value of depends on how far must travel into the sorted prefix.
Best Case ()
Input is already sorted. Every (only the failing comparison at loop entry). The sums collapse to linear terms, giving .
Worst Case ()
Input is reverse-sorted. Each requires moving elements (plus the final failing comparison, so ):
Both sums are , so .
Average Case ()
Assume all permutations of the input are equally likely. On average, half the elements in are smaller than and half are larger, so the inner loop runs times. This yields the same arithmetic progression with a factor of , still . The average case is often the same order of magnitude as the worst case.
Why Worst-Case Matters
- Guarantees: An worst-case bound means the algorithm will never exceed that asymptotic cost for any input. This is essential for real-time and safety-critical systems.
- Adversarial inputs: Worst cases may occur in practice. A human sorting a list is unlikely to provide reverse-sorted input, but programmatic data sources might.
- Average case often equals worst case: For many algorithms (including Insertion Sort), the average and worst cases are the same asymptotic order, so there is no reason to use a weaker analysis.
Analysis vs Benchmarking
| Asymptotic Analysis | Benchmarking |
|---|---|
| Predicts behaviour for all input sizes | Measures behaviour on specific inputs |
| Machine-independent (RAM model) | Machine-dependent (CPU, cache, OS) |
| Ignores constants | Captures real constants |
| Good for algorithm comparison | Good for implementation tuning |
The RAM model analysis is useful for algorithmic decisions (MergeSort over Insertion Sort for large ). Benchmarks become useful for small , where constants dominate.
Summary
| Case | Insertion Sort | Definition |
|---|---|---|
| Best | Already-sorted input | |
| Worst | Reverse-sorted input | |
| Average | Random permutation, each element moves ~ positions | |
| Why worst | Provides guarantees, often similar to average |