Searching: Complexity
Searching is the operation programs perform most often: is this username taken, where is this product, which row has this ID? This lesson compares the cost of the three main approaches, linear search, binary search and hashing, and shows when each one wins.
Linear search: O(n)
Linear search checks the elements one by one. On a list of n elements:
| Case | Comparisons |
|---|---|
| Best (first element) | 1 |
| Average (present, any position equally likely) | (n + 1) / 2 |
| Worst (last element or missing) | n |
Binary search: O(log n)
Binary search halves the range at each step, so it needs at most ⌊log₂ n⌋ + 1 comparisons. On 16 sorted values that is at most 5 steps. Here it searches for 64, the worst case for this array, and needs all 5 steps:
data = [3, 8, 12, 17, 21, 26, 30, 34, 39, 43, 47, 52, 56, 59, 61, 64]
def binary_steps(arr, target):
lo, hi, steps = 0, len(arr) - 1, 0
while lo <= hi:
mid = (lo + hi) // 2
steps += 1
if arr[mid] == target:
return steps
if arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return steps
def linear_steps(arr, target):
for i, v in enumerate(arr):
if v == target:
return i + 1
return len(arr)
print("binary search for 64:", binary_steps(data, 64), "steps")
print("linear search for 64:", linear_steps(data, 64), "steps")
steps = [binary_steps(data, v) for v in data]
print("binary steps per target:", steps)
print("average:", sum(steps) / len(steps), " worst:", max(steps))binary search for 64: 5 steps
linear search for 64: 16 steps
binary steps per target: [4, 3, 4, 2, 4, 3, 4, 1, 4, 3, 4, 2, 4, 3, 4, 5]
average: 3.375 worst: 5
Only one of the 16 values needs 5 steps; the average is about 3.4. Compare that with linear search, whose average is 8.5.
Growing the input
The difference becomes dramatic as n grows. Doubling n doubles linear search's worst case but adds just one step to binary search:
def binary_worst(n):
steps = 0
while n > 0:
steps += 1
n //= 2
return steps
print(f"{'n':>14} {'linear (worst)':>15} {'binary (worst)':>15}")
for exp in [4, 10, 20, 30, 40]:
n = 2 ** exp
print(f"{n:>14,} {n:>15,} {binary_worst(n):>15}") n linear (worst) binary (worst)
16 16 5
1,024 1,024 11
1,048,576 1,048,576 21
1,073,741,824 1,073,741,824 31
1,099,511,627,776 1,099,511,627,776 41
Hash-based search: O(1) on average
A hash set or hash map jumps straight to the right bucket, so a lookup costs about the same whether it holds ten items or ten million. The catch: building the table costs O(n) time and memory first, and the data has no order (no "find the nearest value" or range queries).
The total cost of many searches
Which approach is best depends on how many searches you run on the same data. Sorting costs O(n log n) once; hashing costs O(n) once. Let's estimate the total operations for n = 100,000 items and q searches:
import math
n = 100_000
log_n = math.log2(n)
def linear_total(q): return q * n / 2 # average case
def binary_total(q): return n * log_n + q * log_n # sort once, then search
def hash_total(q): return n + q # build once, then O(1)
print(f"{'searches':>9} {'linear':>15} {'sort + binary':>15} {'hash set':>12} best")
for q in [1, 10, 1_000, 100_000]:
costs = {"linear": linear_total(q), "binary": binary_total(q), "hash": hash_total(q)}
best = min(costs, key=costs.get)
print(f"{q:>9,} {costs['linear']:>15,.0f} {costs['binary']:>15,.0f} {costs['hash']:>12,.0f} {best}") searches linear sort + binary hash set best
1 50,000 1,660,981 100,001 linear
10 500,000 1,661,130 100,010 hash
1,000 50,000,000 1,677,574 101,000 hash
100,000 5,000,000,000 3,321,928 200,000 hash
For a single search, building anything is a waste: linear search wins. As soon as you search repeatedly, a hash set is the clear winner for exact matches. Sorted data + binary search wins when you also need ordering: ranges ("all prices between 10 and 20"), the nearest value, or the k-th smallest.
Summary
| Method | Preparation | Per search | Memory | Supports ranges / nearest? |
|---|---|---|---|---|
| Linear search | none | O(n) |
none | yes, slowly |
| Binary search | sort: O(n log n) |
O(log n) |
none (in place) | yes |
| Hash set / map | build: O(n) |
O(1) average, O(n) worst |
O(n) |
no |
| Balanced BST | build: O(n log n) |
O(log n) |
O(n) |
yes, with fast inserts too |
Tip: In Python,
x in my_listis linear,x in my_setis constant time, andbisectgives you binary search on a sorted list. Choosing the right one is often the biggest performance improvement you can make.
Test yourself
What is the maximum number of comparisons binary search needs on 1,024 sorted values?
- 10
- 11
- 512
- 1,024
You will search the same unsorted list of a million items only once. What is fastest?
- Sort it, then use binary search
- Build a hash set, then look up
- Linear search
- They are all the same
Why might you prefer a sorted list with binary search over a hash set?
- Binary search is O(1)
- You need range queries or the nearest value
- Hash sets can't store numbers
- Sorted lists use more memory