Interpolation Search
Example in TypeScript
function interpolationSearch(arr: number[], target: number): number | null {
let low = 0;
let high = arr.length - 1;
while (low <= high && target >= arr[low] && target <= arr[high]) {
const pos = low + ((target - arr[low]) * (high - low)) / (arr[high] - arr[low]);
const current = arr[Math.floor(pos)];
if (current === target) {
return Math.floor(pos);
}
if (current < target) {
low = Math.floor(pos) + 1;
} else {
high = Math.floor(pos) - 1;
}
}
return null;
}Usage
Last updated