Skip to content

Instantly share code, notes, and snippets.

@Nilesh-Saini-09
Created June 22, 2022 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nilesh-Saini-09/08f7225be6de71ce38d0af33b0bf8f02 to your computer and use it in GitHub Desktop.
Save Nilesh-Saini-09/08f7225be6de71ce38d0af33b0bf8f02 to your computer and use it in GitHub Desktop.
Interpolation Search
// ES6 Arrow Function
const interpolationSearch = (arr, k) => {
let n = arr.length;
let low = 0, high = n - 1;
while(low <= high && k >= arr[low] && k <= arr[high]) {
// finding the position
let pos = low +
Math.floor(((k - arr[low]) * (high - low)) / (arr[high] - arr[low]));
if(arr[pos] < k) {
low = pos + 1;
} else if(arr[pos] > k) {
high = pos - 1;
} else {
return pos;
}
}
return -1;
}
// let testArray = [1,2,3,4,5,6,7,8,9,10];
// let k = 5;
// interpolationSearch(testArray, k);
// output => 4;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment