Skip to content

Instantly share code, notes, and snippets.

@the-mgi
Created November 11, 2020 23:51
Show Gist options
  • Save the-mgi/fb5890f55b40110a82d13015de78a7a9 to your computer and use it in GitHub Desktop.
Save the-mgi/fb5890f55b40110a82d13015de78a7a9 to your computer and use it in GitHub Desktop.
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