Sub topic 10
Worked example: linear search
This chapter assumes you can read Python loops, index into a list, and sum 1 + 2 + ... + n. It applies the best, worst, and average case definitions to one algorithm.
The algorithm and the cost model
Linear search scans a list from the front and stops when it finds the target. The cost model counts one comparison (x == target) per element examined. The input size n is the length of the list.
The function below returns the index and the number of comparisons, so you can read the cost directly.
def linear_search(items, target):
comparisons = 0
for i, x in enumerate(items):
comparisons += 1
if x == target:
return i, comparisons
return -1, comparisons
items = [7, 3, 9, 1, 5]
print(linear_search(items, 7)) # best case: target is first, 1 comparison
print(linear_search(items, 5)) # target is last, n comparisons
print(linear_search(items, 42)) # absent, n comparisonsThe output is (0, 1), (4, 5), and (-1, 5).
Best and worst case
The best case is a target at index 0. The loop stops after 1 comparison, so the cost is 1 for every n.
The worst case is a target at the last index, or a target that is absent. The loop compares against every element, so the cost is n.
| Input | Comparisons |
|---|---|
| Target at index 0 | 1 |
| Target at index n - 1 | n |
| Target absent | n |
Average case
The average case needs an assumption about the input distribution. Assume the target is present and equally likely to be at any of the n positions. A target at index i (counting from 0) costs i + 1 comparisons. The expected cost is the average of those costs:
(1 + 2 + ... + n) / n = (n(n + 1) / 2) / n = (n + 1) / 2
You can check this by running every position.
def linear_search(items, target):
comparisons = 0
for i, x in enumerate(items):
comparisons += 1
if x == target:
return i, comparisons
return -1, comparisons
n = 10
items = list(range(n))
total = sum(linear_search(items, t)[1] for t in items)
print(total / n) # 5.5, which equals (n + 1) / 2Common errors
- Reporting the average as "n / 2" without saying how the count is made. With a 1-based comparison count, the exact value is (n + 1) / 2.
- Forgetting the absent target. It costs n comparisons, which pushes the true average above (n + 1) / 2 whenever misses are possible.
- Treating the best case as typical. The best case is one input out of many.
Exercise
A list has n = 8 elements. The target is present and equally likely to be at any position. What is the expected number of comparisons? Then suppose the target is absent half the time, and otherwise equally likely at any position. What is the expected number now?
Show answer
With the target always present, the expected count is (8 + 1) / 2 = 4.5. With a 50% chance of absence, an absent target costs 8 comparisons, and a present one averages 4.5. The expected count is 0.5 × 8 + 0.5 × 4.5 = 6.25.