← back to algorithms

Searching

Nievergelt & Hinrichs · Ch. 4 · Algorithms and Data Structures

Binary search finds an element in a sorted array in O(log n) by halving the search space at each step. Hash tables achieve O(1) expected time by computing the position directly. Interpolation search guesses smarter when keys are uniformly distributed.

2 5 8 12 15 19 23 27 31 35 target: 15 1 mid=15 2 mid=8, go right 3 mid=12, go right Found at index 4. Three steps for 10 elements.

Binary search

Requires a sorted array:

  1. Compare the target to the middle element.
  2. If equal, done.
  3. If less, search the left half.
  4. If greater, search the right half.

Each step halves the search space: O(log n).

Scheme

Hash tables

Compute a hash function h(key) to find the position directly. Expected O(1) for insert, delete, and lookup. Worst case O(n) if many keys collide. The trade-off: O(1) time for no ordering.

Scheme

Interpolation search

When keys are uniformly distributed, guess where the target is by linear interpolation. Expected O(log log n) for uniform data. Falls back to O(n) in the worst case.

Neighbors

Cross-references

  • ⚙ Ch.5 — trees: BSTs give O(log n) search with ordering