Interpolation Search visualization

Guess where the target should be from its value, like looking up a name in a phone book.

Instead of always probing the middle, estimate the position proportionally: pos = lo + (target − A[lo]) · (hi − lo) / (A[hi] − A[lo]).

On uniformly distributed data it averages O(log log n); on skewed data it can degrade to O(n).

Complexity

Time: best O(1), average O(log log n), worst O(n). Space: O(1). Difficulty: Intermediate.

Pseudocode

procedure interpolationSearch(A, target):
  lo ← 0; hi ← n − 1
  while lo ≤ hi and A[lo] ≤ target ≤ A[hi]:
    pos ← lo + (target−A[lo])·(hi−lo) / (A[hi]−A[lo])
    if A[pos] = target: return pos
    if A[pos] < target: lo ← pos + 1
    else: hi ← pos − 1
  return −1

More searching algorithms