Created
November 11, 2020 23:51
-
-
Save the-mgi/fb5890f55b40110a82d13015de78a7a9 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 BinarySearchIterative(array: number[], key: number): number { | |
let [startIndex, lastIndex] = [0, array.length]; | |
let mid = Math.floor((startIndex + lastIndex) / 2); | |
while (startIndex <= lastIndex) { | |
if (key === array[mid]) { | |
return mid; | |
} else if (key < array[mid]) { | |
lastIndex = mid - 1; | |
} else { | |
startIndex = mid + 1; | |
} | |
mid = Math.floor((startIndex + lastIndex) / 2); | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment