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.
Binary search
Requires a sorted array:
- Compare the target to the middle element.
- If equal, done.
- If less, search the left half.
- 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.