How Search Algorithms Find Things Fast
Finding one item among many is among the most common jobs in computing. A phone looks up a contact, a database finds a customer record, and a compiler finds a variable name. How quickly that lookup happens depends almost entirely on how the data is organized and which search method is used.
The difference can be enormous. With the right approach, a search through a million items can take about twenty steps instead of a million.
Starting simple: linear search
The most basic method is linear search. You start at the first item and check each one in order until you find the target or reach the end.
def linear_search(items, target):
for index, value in enumerate(items):
if value == target:
return index
return -1
Linear search has real strengths. It works on any list, sorted or not, and it is simple enough to get right the first time. For small collections, it is often fast enough that anything fancier is a waste.
Its weakness is growth. In the worst case, it must check every item, so doubling the data doubles the work. This is described as linear time, written O(n).
Binary search: halving the problem
If the data is sorted, you can do much better. Binary search compares the target with the middle item. If the target is smaller, you can discard the entire upper half. If it is larger, you discard the lower half. Then you repeat on what remains.
Think of looking up a name in a printed phone directory. You do not start at page one. You open near the middle, see whether your name comes before or after, and narrow down quickly.
def binary_search(items, target):
low, high = 0, len(items) - 1
while low <= high:
middle = (low + high) // 2
if items[middle] == target:
return middle
if items[middle] < target:
low = middle + 1
else:
high = middle - 1
return -1
Each step halves the search area, so the number of steps grows very slowly. This is logarithmic time, written O(log n). A sorted list of about a million items needs roughly twenty comparisons at most. Doubling the data adds just one more step.
The catch is the requirement: the data must be sorted, and it must allow quick access to its middle. Sorting costs time itself, so binary search pays off when you search many times after sorting once.
Hash tables: jumping straight to the answer
A hash table takes a different approach. Instead of comparing, it uses a hash function to turn a key into a number, and that number points to a position where the value is stored. Lookup becomes a direct jump rather than a search.
Python dictionaries and sets, and similar structures in most languages, work this way. On average, a lookup takes constant time, written O(1), regardless of how many items are stored.
Two things limit hash tables. Different keys can occasionally land in the same position, called a collision, and the structure must have a way to resolve it. They also do not keep items in sorted order, so they are poor at questions such as "give me everything between A and F."
Trees: sorted structure that can grow
A binary search tree organizes items so that, at each node, smaller values sit on the left and larger values sit on the right. Searching follows one branch at each step, much like binary search, discarding half the remaining items in a balanced tree.
Trees handle insertions and deletions more gracefully than sorted arrays, which must shift items around. A plain tree can become lopsided if data arrives in order, which slows it down. Self-balancing trees such as red-black trees and B-trees keep their height small automatically.
Databases rely heavily on B-trees. They are designed to work well with storage that reads data in blocks, so a lookup in a table with millions of rows needs only a handful of reads. This is what an index does when you ask a database to speed up a query.
Searching beyond simple lookups
Not every search is for an exact value.
- Text search may use an inverted index, which maps each word to the documents that contain it, so a query does not scan every page.
- Graph search uses methods like breadth-first and depth-first search to find routes through connected data, such as roads or links between pages.
- Approximate or similarity search finds items close to a query rather than equal to it, often using specialized indexes.
Choosing a method
The right choice depends on your data and your usage pattern.
- Small or unsorted data, few searches: linear search is fine.
- Sorted data, many lookups: binary search or a sorted index.
- Exact-match lookups by key: a hash table.
- Ordered data with frequent changes, range queries: a balanced tree or database index.
There is also a trade-off between time and memory. Indexes and hash tables speed up searching but use extra space and need upkeep when data changes.
Why this matters
Understanding how search scales explains many everyday performance problems. A page that slows to a crawl as data grows is often doing a linear scan where an index or hash lookup would do. Choosing the right structure early often matters more than micro-tuning code later.
Frequently Asked Questions
Why does binary search need sorted data?
Because each step relies on knowing which half can be thrown away. In a sorted list, comparing the target with the middle item tells you which side it must be on. In an unsorted list, that comparison tells you nothing.
Is a hash table always faster than binary search?
On average, lookups in a hash table are faster, since they take constant time. But hash tables do not keep order and can suffer from collisions, so binary search or a tree is better when you need ordered results or range queries.
What does O(log n) actually mean?
It describes how the number of steps grows as the data grows. For logarithmic time, doubling the data adds only a small, fixed number of steps, which is why methods like binary search stay fast even on very large collections.