Best, Average and Worst Case Analysis, With Examples
"Linear search is O(n)" sounds like one fact, but the number of steps linear search takes depends on where the target is. If it is first, the search takes one comparison. If it is missing, it takes n. Best, average and worst case are three different ways of turning "it depends on the input" into a single function of n. This guide defines each, works through linear search, insertion sort and quicksort, and clears up the most common confusion in the subject.
The three cases, defined
Fix an input size n. Among all inputs of that size:
- the worst case is the largest number of steps the algorithm takes on any of them;
- the best case is the smallest number of steps on any of them;
- the average case is the expected number of steps when inputs are drawn from a stated probability distribution.
Each of these is a function of n, and each can then be described with O, Omega or Theta as in the Big O guide. The average case is the only one that needs extra information: you cannot compute an average without saying what you are averaging over.
Linear search
Linear search checks items one by one until it finds the target or runs out.
- Best case: the target is the first item. 1 comparison, Theta(1).
- Worst case: the target is last or absent. n comparisons, Theta(n).
- Average case: assume the target is present and equally likely to be at any of the n positions. The expected count is (1 + 2 + ... + n) / n = (n + 1) / 2, which is still Theta(n). The average is about half the worst case, and halving is a constant factor.
Examples use Python 3.10 or later and only the standard library. This script counts comparisons on a list of the 100 numbers from 100 to 199.
def linear_search(items, target):
comparisons = 0
for index, value in enumerate(items):
comparisons += 1
if value == target:
return index, comparisons
return -1, comparisons
items = list(range(100, 200))
for target in [100, 149, 199, 500]:
print(target, linear_search(items, target))
total = sum(linear_search(items, t)[1] for t in items)
print("average for a present key:", total / len(items))
Output (target, then index and comparisons):
100 (0, 1)
149 (49, 50)
199 (99, 100)
500 (-1, 100)
average for a present key: 50.5
The first element costs 1 comparison, the middle one 50, the last one 100, and a missing key also 100. Averaged over all 100 present keys, the count is 50.5, exactly (n + 1) / 2. If you assumed instead that the target is missing half the time, the average would change; that is what "the average case depends on the distribution" means in practice.
Insertion sort
Insertion sort takes each item in turn and shifts it left past every larger item already in the sorted prefix.
- Best case: already sorted input. Each new item is compared once with its left neighbor and stays put: n - 1 comparisons, Theta(n).
- Worst case: reversed input. Item i must move past all i items before it: 1 + 2 + ... + (n - 1) = n(n - 1)/2 comparisons, Theta(n^2).
- Average case: for a random ordering of distinct keys, each pair of items is out of order with probability one half, so the expected number of shifts is about n(n - 1)/4. Still Theta(n^2).
import random
def insertion_sort_comparisons(items):
items = list(items)
comparisons = 0
for i in range(1, len(items)):
key = items[i]
j = i - 1
while j >= 0:
comparisons += 1
if items[j] <= key:
break
items[j + 1] = items[j]
j -= 1
items[j + 1] = key
return comparisons
random.seed(42)
n = 10
shuffled = random.sample(range(n), n)
print("sorted: ", insertion_sort_comparisons(range(n)))
print("shuffled:", insertion_sort_comparisons(shuffled))
print("reversed:", insertion_sort_comparisons(range(n - 1, -1, -1)))
Output:
sorted: 9
shuffled: 25
reversed: 45
For n = 10 the sorted input needs 9 comparisons and the reversed input needs 45, which is 10 x 9 / 2. The shuffled list (one fixed ordering, from random.seed(42)) falls in between. Because the best case is linear, insertion sort is a sensible choice for input that is already nearly sorted.
Quicksort
Quicksort picks a pivot, partitions the items into those smaller and those larger, and sorts each side recursively.
- Average case: O(n log n), in fact Theta(n log n), when every ordering of the input is equally likely (or when the pivot is chosen at random, which gives the same expected time for every input).
- Worst case: Theta(n^2). It happens when every pivot is the smallest or largest remaining item, so each partition peels off a single element. A first-element pivot on already sorted input does exactly this.
- Best case: Theta(n log n) for distinct keys, when every pivot splits the items roughly in half.
Quicksort is the standard example of an algorithm whose average case and worst case differ in class. The merge sort and quicksort guide covers pivot choice and how to avoid the bad case.
Why worst case is the usual guarantee
- It is a promise. A worst-case bound holds for every input, including inputs chosen by an adversary or produced by an unlucky upstream process.
- It needs no assumptions. The average case is only as good as the assumed distribution. Real data is often sorted, nearly sorted or full of duplicates, which is far from "every ordering equally likely".
- It is often the typical case too. For linear search, merge sort and many others, the average and worst case are the same class.
Average-case bounds are still useful when the assumption is justified, or when the algorithm makes its own randomness (random pivots, random hashing), because then the average is over the algorithm's coin flips, not over inputs you do not control.
A related idea that is not an average at all is amortized cost: the total over any sequence of operations divided by their number. It involves no probability. The amortized analysis guide explains the difference.
The common confusion: cases are not bounds
It is tempting to match the words up: worst case with O, best case with Omega, average case with Theta. That is wrong, and it causes real mistakes.
- A case picks which function you are talking about: the worst-case count W(n), the best-case count B(n) or the average A(n).
- A bound (O, Omega, Theta) describes how that function grows.
Every combination makes sense. For insertion sort, W(n) = n(n - 1)/2, so the worst case is O(n^2), Omega(n^2) and therefore Theta(n^2). B(n) = n - 1, so the best case is Theta(n). Saying "the best case of insertion sort is Omega(n^2)" is false, and saying "the worst case is O(n^3)" is true but loose.
What you can say about insertion sort as a whole, across all inputs of size n, is that its running time is O(n^2) (no input is worse than the worst case) and Omega(n) (no input is better than the best case). Those two statements are where the "worst goes with O, best goes with Omega" intuition comes from. They are statements about the range of running times, not definitions of the cases.
Seeing the cases side by side
The Algorithm Comparison Tool has a best, average and worst case selector over a fixed table of eight algorithms, and evaluates each one's stated class at your n. At n = 1000 in the best case, linear and binary search both score 1 and bubble sort 1,000. Switch to the worst case and quicksort moves from 9,965.78 to 1,000,000, beside bubble sort. Two simplifications in that table are worth knowing: bubble sort's O(n) best case assumes the version that stops after a pass with no swaps, and quicksort's O(log n) space is the average recursion depth (the worst case is O(n) unless you recurse into the smaller side first).
Check yourself
- What is the best case of binary search, and the worst? (Theta(1) when the middle item is the target; Theta(log n) otherwise in the worst case.)
- True or false: an algorithm with worst case Theta(n log n) can have a best case of Theta(n). (True: a natural merge sort, which detects runs that are already in order, makes n - 1 comparisons on sorted input and is Theta(n log n) in the worst case.)
- Why can't you state an average case for an algorithm without more information? (Because an average needs a distribution over inputs.)