Skip to main content

Searching Algorithms — Overview

Overview

Searching looks trivial and hides the most useful trade-off in the field: how much do you pay up front to make later lookups cheap? Linear search pays nothing and costs O(n) every time. Binary search costs O(n log n) to sort first, then O(log n) forever. A hash table pays O(n) to build and O(1) per lookup.

Which is right depends entirely on the ratio of lookups to changes — a question about your workload, not about the algorithms.

In This Section

  • Linear Search — check each element. No preconditions, no preparation.
  • Binary Search — halve the space each step. Requires sorted data, and is notoriously easy to get subtly wrong.

The Options, Compared

ApproachPreparationPer lookupRequiresAlso gives you
Linear searchNoneO(n)NothingWorks on any sequence, any predicate
Binary searchO(n log n) sortO(log n)Sorted, random accessRange queries, nearest match, insertion point
Hash tableO(n) buildO(1) expectedHashable keysNothing else — no ordering
Balanced BSTO(n log n) buildO(log n)Comparable keysOrdering, ranges, and cheap updates

Deciding

The break-even is worth internalising: sorting to enable binary search only pays off after roughly log₂ n lookups. For a thousand elements that is about ten searches. Below that, scan.

Do not sort inside a loop to enable a binary search

This is a genuinely common performance bug: sorting costs O(n log n) and the binary search saves O(n) − O(log n) per lookup, so re-sorting per lookup is strictly worse than never sorting at all. Sort once outside the loop, or use a hash table.