Search Algorithms

The family of search methods and when each one wins: linear scan, binary search and its boundary form, exponential search for unknown sizes, interpolation search for evenly spread keys, peak finding, and binary search on the answer.

Overview

Every search answers one question: where is the thing I want, or where would it go? What you know about the data decides how fast you can answer. With no order you must look at everything. With sorted data you can throw away half of what is left at each step. With more knowledge (how the values are spread, or that they rise and then fall) you can do better still.

This chapter walks through the searches in that order, from the one that needs nothing to the ones that need the most. Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.

Pick the search that fits the data

The rule: ask what the data guarantees, because each extra guarantee buys a faster search.

Notice the one fork among the sorted cases: if you know the size, use binary search; if you do not, use exponential search. The sections below take each search in turn, starting with the baseline.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio