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 -1

What are the best, worst and average cases?

Count: comparisons in the worst case (target absent).

Measured counts

02000400020004000ncount
Measured
Table
ncount
88
1616
3232
6464
128128
256256
512512
10241,024
20482,048
40964,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)
  1. Best case: the target is first, 1 comparison.
  2. Worst case: absent or last, n comparisons.
  3. 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.