function interpolationSearch(array: number[], target: number) {let low = 0, high = array.length - 1;
while (low <= high && target >= array[low] && target <= array[high]) {const position = low + Math.floor(((target - array[low]) * (high - low)) / (array[high] - array[low]));
if (array[position] === target) return position;
if (array[position] < target) low = position + 1;
else high = position - 1;
}
return -1;
}
Look for 33 in [0, 31]. The values run from 7 to 97, so the position can be estimated by proportion.
Understanding Interpolation search
The idea
Binary search always probes the middle. Interpolation search probes where the target would be if the values were spread evenly: a target near the low end of the value range gets a probe near the low end of the index range. The estimate is a straight-line interpolation between the two ends.
When the values really are uniform the range shrinks from n to about √n per probe, which gives log log n probes: four for a million elements. When they are not, a skewed distribution can push every probe one step at a time and the search degrades to linear.
The four stages
Complexity
Versus its siblings
Pseudocode
INTERPOLATIONSEARCH(array, target)
low ← 0; high ← n − 1
while low ≤ high and array[low] ≤ target ≤ array[high]
position ← low + ⌊(target − array[low]) × (high − low) / (array[high] − array[low])⌋
if array[position] = target: return position
if array[position] < target: low ← position + 1 else high ← position − 1
return −1
When to use
Pitfalls
History
W. W. Peterson proposed it in 1957 for searching sorted files on disk. Yehoshua Perl, Alon Itai and Haim Avni proved the log log n average in 1978, and Gonnet showed how badly it can do on non-uniform data, which is why binary search stayed the default.