Sub topic 9
Computing the average as an expected value
This chapter assumes you can read short Python programs and sum series such as 1 + 2 + ... + n. It also assumes you know that the average case is a cost taken over a distribution of inputs.
The formula
The average case is an expected value. List every possible input of size n. Give each input a probability, and multiply that probability by the number of operations the algorithm uses on that input. The sum of those products is the expected cost:
E[T(n)] = sum over inputs x of P(x) · T(x)
The probabilities must add up to 1. The result depends on the distribution you choose, so state it before you compute anything.
Linear search with a uniform target
Suppose the target is in the list and is equally likely to be at any of three positions. Each position has probability 1/3, and finding the target at position i costs i comparisons.
| Target position | Probability | Comparisons | Contribution |
|---|---|---|---|
| 1 | 1/3 | 1 | 1/3 |
| 2 | 1/3 | 2 | 2/3 |
| 3 | 1/3 | 3 | 3/3 |
The sum is 6/3 = 2. For general n, the expected cost is (1 + 2 + ... + n) / n = (n + 1) / 2. This is the value the earlier code example printed, 5.5 for n = 10.
Changing the assumption changes the answer
Now allow the target to be missing. Let q be the probability that it is present. If it is present, it is uniform over the positions. If it is absent, the search makes n comparisons.
E = q · (n + 1) / 2 + (1 − q) · n
from fractions import Fraction
def expected_comparisons(n, p_present):
present_cost = Fraction(n + 1, 2) # uniform over positions 1..n
absent_cost = Fraction(n) # a miss scans the whole list
return p_present * present_cost + (1 - p_present) * absent_cost
print(expected_comparisons(10, Fraction(1))) # 11/2, always present
print(expected_comparisons(10, Fraction(1, 2))) # 31/4, present half the time
print(expected_comparisons(10, Fraction(0))) # 10, always absentThe three outputs are 5.5, 7.75, and 10. The algorithm and n are the same each time. Only the distribution changed.
Common errors
- Leaving the distribution unstated. "The average is (n + 1) / 2" is only true under the uniform, target-present assumption.
- Probabilities that do not sum to 1. Check the total before you multiply.
- Mixing up cases and positions. A cost of i comparisons belongs to position i, not to the whole list.
- Treating the average as typical. An expected value of 7.75 comparisons is never the cost of any single run. It is a mean over many runs.
Exercise
A linear search runs on a list of n = 4 items. The target is equally likely to be at positions 1, 2, 3, or 4, or to be absent, so each of the five outcomes has probability 1/5. What is the expected number of comparisons?
Show answer
The costs are 1, 2, 3, 4 for the four positions and 4 for the absent case. The expected value is (1 + 2 + 3 + 4 + 4) / 5 = 14/5 = 2.8 comparisons.