Last active
October 1, 2022 04:24
-
-
Save mohnish/a83e5bfab2b884fafa9717ea1066c6c4 to your computer and use it in GitHub Desktop.
Binary Search in JavaScript
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 binarySearch(list, key) { | |
let low = 0; | |
let high = list.length - 1; | |
while (low <= high) { | |
let mid = low + Math.floor((high - low) / 2); | |
if (key < list[mid]) { | |
high = mid - 1; | |
} else if (key > list[mid]) { | |
low = mid + 1; | |
} else { | |
return mid; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment