Last active
November 28, 2020 11:17
-
-
Save the-mgi/3c954abb71c194f089a35cd6bee95e71 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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