Exercise 25 of 30 · beginner · best case · worst case · average case · linear
Linear search that stops early
The code
def find(items, target):
for i, x in enumerate(items):
if x == target:
return i
return -1What are the best, worst and average cases?
Count: comparisons in the worst case (target absent).
Measured counts
Table
| n | count |
|---|---|
| 8 | 8 |
| 16 | 16 |
| 32 | 32 |
| 64 | 64 |
| 128 | 128 |
| 256 | 256 |
| 512 | 512 |
| 1024 | 1,024 |
| 2048 | 2,048 |
| 4096 | 4,096 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Best Θ(1), worst Θ(n), average Θ(n)
- Extra space
- O(1)
- Exact count
- n (worst case)
- Best case: the target is first, 1 comparison.
- Worst case: absent or last, n comparisons.
- Average over a uniformly random position of a present target: (n + 1)/2 comparisons, still Θ(n).
Common mistake: Saying "linear search is O(1)" because of the best case. State which case you mean.
Check: measured count ÷ (n) settles near 1.00 for large n.