Skip to content

Instantly share code, notes, and snippets.

@the-mgi
Last active November 28, 2020 11:17
Show Gist options
  • Select an option

  • Save the-mgi/3c954abb71c194f089a35cd6bee95e71 to your computer and use it in GitHub Desktop.

Select an option

Save the-mgi/3c954abb71c194f089a35cd6bee95e71 to your computer and use it in GitHub Desktop.
function InterpolationSearchIterative(array: number[], key: number): number {
let startIndex = 0;
let lastIndex = array.length - 1;
// 1st condition, to make sure we are not out of bounds of array
// 2nd and 3rd condition to make sure that the key would be present in indexes [startIndex, lastIndex]
while (startIndex <= lastIndex && key >= array[startIndex] && key <= array[lastIndex]) {
const position =
Math.floor(startIndex + (
(lastIndex - startIndex) /
(array[lastIndex] - array[startIndex]) *
(key - array[startIndex])));
if (array[position] === key) {
return position;
} else if (array[position] > key) {
lastIndex = position - 1;
} else {
startIndex = position + 1;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment