Sub topic 8
Average case: cost over a distribution of inputs
This chapter assumes you can read short Python loops and sum simple series like 1 + 2 + ... + n. It also assumes you know that best and worst case are the cheapest and most expensive inputs of a given size.
What the average case measures
Inputs of the same size n can cost different amounts. The best case takes the cheapest input. The worst case takes the most expensive one. The average case asks a different question: how much does a typical run cost?
"Typical" has no meaning until you say which inputs are likely. The average case is the cost of each input, weighted by the probability of that input, and then summed. The probabilities form the input distribution.
The formula
Let the possible inputs of size n be x1, x2, and so on. Let P(x) be the probability of input x, and let cost(x) be its operation count. Then:
average cost = sum over all inputs x of P(x) × cost(x)
The probabilities must add up to 1. If every input is equally likely, the formula reduces to the plain mean of the costs.
The distribution changes the answer
Suppose a search scans a list of 4 items. If the target sits at position i (counting from 0), the scan costs i + 1 comparisons. The code below computes the average cost under two different distributions.
def cost(position):
return position + 1
def average_cost(probs):
return sum(p * cost(i) for i, p in enumerate(probs))
n = 4
uniform = [1 / n] * n # every position equally likely
skewed = [0.7, 0.2, 0.05, 0.05] # target is usually near the front
print(round(average_cost(uniform), 2)) # 2.5
print(round(average_cost(skewed), 2)) # 1.45The algorithm, the input size, and the cost model are identical in both runs. Only the distribution changed, and the average dropped from 2.5 to 1.45. An average case figure is therefore always conditional on an assumption.
Where the assumption can fail
- Real inputs are often not uniform. Logs, user queries, and partly sorted data all have structure.
- A model that is wrong in one direction can make an algorithm look better than it performs in practice.
- The average hides spread. Two algorithms can share an average while one has rare, very expensive runs.
For these reasons, state the distribution you used next to every average case result. If you cannot justify it, the worst case is the safer claim.
Exercise
A scan of 3 items costs 1, 2, or 3 comparisons depending on where the target is. The target is at position 0 with probability 0.5, at position 1 with probability 0.3, and at position 2 with probability 0.2. What is the average cost?
Show answer
Average cost = 0.5 × 1 + 0.3 × 2 + 0.2 × 3 = 0.5 + 0.6 + 0.6 = 1.7 comparisons. The probabilities sum to 1, so this is a valid weighted average.