Created
November 28, 2020 11:16
-
-
Save the-mgi/6f6b12e98a16850e800a2ce6dfddd420 to your computer and use it in GitHub Desktop.
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
function InterpolationSearchRecursive(array: number[], key: number, startIndex: number, lastIndex: number): number { | |
const position = | |
Math.floor(startIndex + ( | |
(lastIndex - startIndex) / | |
(array[lastIndex] - array[startIndex]) * | |
(key - array[startIndex]))); | |
// 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] | |
if (startIndex <= lastIndex && key >= array[startIndex] && key <= array[lastIndex]) { | |
if (array[position] === key) { | |
return position; | |
} else if (key < array[position]) { | |
lastIndex = position - 1; | |
} else { | |
startIndex = position + 1; | |
} | |
return InterpolationSearchRecursive(array, key, startIndex, lastIndex); | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment