Sub topic 14
Choosing the Right Search
This chapter assumes you can already write linear search and binary search, and that you know the lower-bound variant and the bisect module from earlier chapters. You should also be comfortable reading Big-O expressions such as O(n), O(log n), and O(n log n). The goal here is a decision: given a real collection and a real workload, which search should you use?
Big-O complexity alone does not settle the choice. Binary search is O(log n) per query, but only after the data is sorted, and sorting costs O(n log n). Linear search is O(n) per query, but it works on anything you can iterate over, needs no setup, and has very low constant factors. The right answer depends on several things:
- how large the collection is
- whether it is already sorted or can stay sorted
- how often you search it compared with how often you change it
- whether the data structure supports fast access by index
The Factors That Decide
Data size
For small collections, the difference between n and log n is tiny. With 16 elements, linear search does at most 16 comparisons and binary search does at most 5. Each linear step is very cheap: it reads the next memory location, which is probably already in the CPU cache, and the loop's branch is easy for the processor to predict. Each binary step jumps to a new location and takes a branch that is hard to predict. On tiny arrays, a straight scan is often as fast as binary search or faster.
As n grows, the gap becomes large. At one million elements, a linear search that misses does one million comparisons. Binary search does about 20.
Ordering
Binary search is only correct on data sorted by the same ordering your comparisons use. If the data arrives unsorted, you have to pay for a sort before the first binary search. If the data is sorted by one key (say, by date) and you search by another (say, by name), the existing order does not help you.
Search frequency versus change frequency
A single search on unsorted data should almost always be linear: O(n) is cheaper than O(n log n) + O(log n). Many searches on data that rarely changes favor sorting once and then using binary search. Data that changes constantly pushes the other way, because keeping an array sorted costs O(n) per insertion in the worst case: every element after the insertion point has to shift.
Access pattern of the structure
Binary search needs random access, meaning you can reach a[mid] in constant time. Arrays and Python lists have it. Linked lists do not. Reaching the middle of a linked list means walking n/2 nodes, so a "binary search" on a linked list still takes O(n) time and is usually slower than a plain scan.
Paying Off the Cost of Sorting
Suppose you start with n unsorted items and expect k searches. A rough cost model:
- Linear only: about k × n/2 comparisons for successful searches (k × n if most searches miss).
- Sort, then binary: about n log₂ n for the sort plus k × log₂ n for the searches.
Sorting pays off once k is large enough that the savings per query cover the sort. The script below solves for that break-even k under this simple model.
import math
def break_even_queries(n):
"""Smallest k where sorting once plus k binary searches beats
k linear searches, assuming n/2 comparisons per linear search."""
sort_cost = n * math.log2(n)
linear_per_query = n / 2
binary_per_query = math.log2(n)
saving_per_query = linear_per_query - binary_per_query
if saving_per_query <= 0:
return None # n too small for binary search to save anything
return math.ceil(sort_cost / saving_per_query)
for n in [100, 1_000, 1_000_000]:
print(n, break_even_queries(n))
# 100 16
# 1000 21
# 1000000 40The break-even point grows very slowly. Even at a million elements, about 40 searches are enough to justify a sort. The model ignores constant factors: real sorts are well optimized, and real comparisons differ in cost. Treat these numbers as orders of magnitude rather than exact thresholds. The conclusion holds up in practice: if you will search the same data more than a few dozen times, sorting first is usually worth it.
Measuring Instead of Guessing
Cost models point you in the right direction, and measurement confirms it. The script below compares three ways of answering 500 membership queries against 50,000 integers. It uses a linear scan (Python's in on a list), binary search with bisect_left, and a hash-based set.
import bisect
import random
import timeit
random.seed(42)
n = 50_000
data = random.sample(range(10 * n), n)
targets = random.sample(range(10 * n), 500)
sorted_data = sorted(data)
as_set = set(data)
def linear_all():
return sum(1 for t in targets if t in data)
def binary_all():
count = 0
for t in targets:
i = bisect.bisect_left(sorted_data, t)
if i < len(sorted_data) and sorted_data[i] == t:
count += 1
return count
def set_all():
return sum(1 for t in targets if t in as_set)
assert linear_all() == binary_all() == set_all()
for name, fn in [("linear", linear_all), ("binary", binary_all), ("set", set_all)]:
seconds = timeit.timeit(fn, number=3) / 3
print(f"{name:>6}: {seconds * 1000:.3f} ms")
sort_seconds = timeit.timeit(lambda: sorted(data), number=3) / 3
print(f" sort: {sort_seconds * 1000:.3f} ms (one-time cost)")On typical hardware, the linear version takes hundreds of times longer than the binary version. The set is faster still. Exact figures depend on your machine. The ranking stays the same.
When Neither Is the Best Answer
If all you need is "is x present?" or "what value goes with key x?", a hash table (Python set and dict, Java HashSet and HashMap) gives O(1) average lookups. Neither linear nor binary search can match that. Binary search on a sorted array still wins in several situations:
- Range queries: "all values between 10 and 20" needs two bound searches and a slice. A hash table cannot answer it without scanning everything.
- Nearest-value queries: "the smallest value ≥ x" is a lower-bound search. Hashing destroys order.
- Memory: a sorted array has no per-entry overhead. Hash tables keep spare buckets so lookups stay fast.
- Searching over an answer range: binary search on a monotonic predicate has no stored collection at all, so a hash table is not an option.
If you need both frequent updates and ordered queries, a balanced search tree or a sorted container library gives O(log n) for inserts and searches. It costs more memory and has higher constant factors than a plain sorted array.
A Decision Procedure
The same reasoning as a reference table:
| Situation | Recommended approach | Reason |
|---|---|---|
| One-off search on unsorted data | Linear search | Sorting costs more than one scan |
| Tiny collection (a few dozen items) | Linear search | Simpler code, cache-friendly, gap is negligible |
| Large, sorted, read-mostly array | Binary search | O(log n) per query with no setup |
| Large, unsorted, searched many times | Sort once, then binary search | Sort cost is repaid after a few dozen queries |
| Frequent inserts and deletes, ordered queries | Balanced tree or sorted container | Sorted arrays pay O(n) per insert |
| Exact-match membership only | Hash set or map | O(1) average lookup |
| Linked list or forward-only stream | Linear search | No random access, so halving does not help |
| Finding a threshold in a numeric range | Binary search on a predicate | No collection to scan, only a monotonic test |
Common Mistakes
- Sorting inside the search function. If
search(items, x)callssorted(items)on every call, each query costs O(n log n), which is worse than linear search. Sort once, outside the loop. - Assuming data stays sorted. Code that appends to a sorted list with
appendinstead ofbisect.insortquietly breaks the precondition, and later binary searches return wrong answers without raising any error. - Optimizing the wrong thing. If a list of 20 configuration entries is searched once at startup, linear search is correct, and anything more complex adds risk for no gain.
- Using binary search where a set would do. If you never need order, a hash-based structure is simpler and faster.
- Sorting by the wrong key. Binary search with a key function, such as
bisect_left(a, x, key=...)(available since Python 3.10), only works ifawas sorted by that same key.
Exercises
Exercise
You receive an unsorted list of 200,000 user IDs and must check whether 3 specific IDs are present, once. Which approach should you use and why?
Show answer
Use linear search (or Python's in on the list). Three scans cost about 600,000 comparisons in the worst case. Sorting first costs roughly 200,000 × 18 ≈ 3.6 million comparisons before any search runs. With so few queries, the sort never pays off.
Exercise
A product catalog of 2 million items is loaded at startup and then queried thousands of times per second for "all products priced between A and B". Items are added once a day. What should you use?
Show answer
Sort the catalog by price once at load time (and again after the daily update), then answer each query with two bound searches: bisect_left for A and bisect_right for B, and return the slice between them. A hash table cannot answer range queries, and linear search would scan 2 million items per query.
Exercise
A colleague's function is def contains(items, x): s = sorted(items); i = bisect.bisect_left(s, x); return i < len(s) and s[i] == x. It is called in a loop 10,000 times on the same 100,000-element list. What is wrong, and how do you fix it?
Show answer
It sorts on every call, so each call costs O(n log n) and the loop does about 10,000 sorts. That is slower than plain linear search. Sort once before the loop and pass the sorted list in. If only membership matters, build a set once and use x in s.
Exercise
Using the break-even model from this chapter, roughly how many searches does it take before sorting 1,000 unsorted items pays off? Why is the real number only approximate?
Show answer
About 21 searches: sort cost 1,000 × log₂(1,000) ≈ 9,966, divided by a per-query saving of 500 − 10 ≈ 490. The figure is approximate because the model counts comparisons only. It ignores constant factors such as cache behavior, branch prediction, the speed of the built-in sort, and whether searches mostly hit or miss.