-
-
Save Nilesh-Saini-09/08f7225be6de71ce38d0af33b0bf8f02 to your computer and use it in GitHub Desktop.
Interpolation Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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