Algorithms · Visualized
Searching Algorithms
Searching Algorithms
Six search strategies on a sorted array — from the obvious linear scan to log-time binary search and beyond.
Big-O: Binary O(log n), Linear O(n), Jump O(√n), Interpolation O(log log n) avg, Exponential O(log n).
Searching Algorithms
Finding a target — or proving it is absent — as cheaply as the data structure allows.
Searching locates a target value (or an answer) inside structured data. The right algorithm depends entirely on what structure exists: unsorted data only supports scanning every element, but sorted data lets each probe discard half of the remaining range, which is why binary search runs in O(log n) — a million items need about 20 probes.
The general recipe
- Identify the structure: unsorted list → linear or hash-based; sorted list/array → binary-family search.
- Define the probe: pick an index (middle, interpolation estimate, jump point) and compare it with the target.
- Shrink the range: discard the half (or block) that cannot contain the target.
- Handle the boundaries: decide what "not found" returns (−1, insertion point) and stop when the range is empty.
- For answer-search variants, binary search on a monotone predicate rather than on array values.
Vocabulary you'll meet everywhere here
- Linear search
- scan left to right, O(n) — the only option on unsorted data
- Binary search
- halve the range each probe, O(log n), requires sorted input
- Jump search
- hop in blocks of √n then linear-scan the block, O(√n)
- Interpolation search
- probe the position the value "should" be at, O(log log n) on uniformly distributed keys
- Exponential search
- find a range by doubling (1, 2, 4, …), then binary search inside it, O(log i) where i is the target index
Where this family shows up
- Dictionary and phone-book lookups, autocompletion on sorted word lists
- Database indexes (B-trees) are generalized binary search over disk pages
- Binary search on the answer: minimum capacity, speed or rate that satisfies a monotone condition
Common pitfalls
- mid = (lo + hi) / 2 can overflow in fixed-width languages — use lo + (hi − lo) / 2
- Wrong loop condition (lo < hi vs lo <= hi) is the classic off-by-one that skips or revisits elements
- Running binary search on unsorted data silently returns wrong answers — validate the precondition
- Setting lo = mid instead of mid + 1 can cause infinite loops when the range narrows to two elements
def binary_search(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.