Sub topic 14
Choosing the Right Search
This chapter assumes you know how linear search and binary search work, and that you can read Big-O costs such as O(n), O(log n), and O(n log n). You have already seen that binary search is much faster for a single lookup. That speed comes with conditions, though, and in some common situations linear search is the better choice.
The Hidden Cost: Getting Sorted Data
Binary search only works on sorted data. If your data is already sorted, each lookup costs O(log n). If it isn't sorted, you first have to sort it, which costs O(n log n). That is more expensive than one linear scan at O(n).
The real question is how many times you will search. Suppose you run k searches on n elements:
| Strategy | Total cost |
|---|---|
| Linear search k times | k · n |
| Sort once, then binary search k times | n log n + k log n |
Sorting pays off once k grows past roughly log₂ n. For a million elements, that is about 20 searches. Below that number, scanning is usually cheaper.
The following script applies this cost model to a few sizes. It counts worst-case comparisons and ignores constant factors, so treat it as a rough guide.
import math
def linear_cost(n, k):
return k * n
def sort_then_binary_cost(n, k):
return n * math.log2(n) + k * math.log2(n)
for n in (16, 1_000, 1_000_000):
for k in (1, 10, 1_000):
lin = linear_cost(n, k)
srt = sort_then_binary_cost(n, k)
winner = "linear" if lin <= srt else "sort + binary"
print(f"n={n:>9,} k={k:>5}: {winner}")The output shows that for one or ten searches, linear search wins even on a million elements. At a thousand searches, sorting first wins at every size.
Factors Beyond Big-O
Small inputs. For a few dozen elements, a linear scan often runs faster than binary search in practice. It walks memory in order, which suits the CPU cache, and its branches are easy for the processor to predict. Big-O hides these constant factors.
Frequent updates. Keeping an array sorted means each insertion shifts elements over, which costs O(n). If the data changes about as often as you search it, the effort of keeping it sorted can cancel out the faster lookups.
No random access. Binary search has to jump straight to the middle element. On a linked list, reaching the middle takes O(n) steps, so binary search loses its advantage there. Use linear search on linked lists.
Range and nearest-value queries. If you need "the first value ≥ x" or "how many values fall between a and b," sorted data with lower-bound and upper-bound searches is the right tool. Linear search can answer these questions, but only by scanning everything.
A Decision Guide
Summary of Trade-offs
| Situation | Better choice |
|---|---|
| One-off lookup in unsorted data | Linear search |
| Many lookups in static data | Sort once, then binary search |
| Tiny arrays (tens of elements) | Linear search |
| Linked list | Linear search |
| Insertion points, ranges, duplicate counts | Binary search (lower/upper bound) |
| Exact membership only, no order needed | Hash set |
Exercise
You have an unsorted array of 500,000 log records and need to answer 3 lookup queries, then throw the array away. Should you sort it and use binary search? Justify with approximate costs.
Show answer
No. Three linear searches cost about 3 × 500,000 = 1.5 million comparisons. Sorting alone costs about 500,000 × log₂(500,000) ≈ 500,000 × 19 ≈ 9.5 million comparisons, before any search runs. Linear search is cheaper because k = 3 is far below log₂ n ≈ 19.
Exercise
A sorted array of user IDs receives one new ID for every lookup it serves. Why might binary search on this array perform worse than you expect, and what could you use instead?
Show answer
Each insertion into a sorted array shifts elements over, costing O(n). That cost dominates the O(log n) lookups, so each insert-plus-lookup pair costs O(n) overall. A hash set handles exact lookups and inserts in O(1) on average. If you need ordered queries, use a balanced search tree, which does both operations in O(log n).