Created
February 18, 2022 17:48
-
-
Save omargfh/e295785f3c223d7cba60919548d28eb1 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
const binary_search = (arr, q) => { | |
const halfway = (l, h) => { return Math.floor((l + h) / 2) } | |
const strcmp = ( str1, str2 ) => { | |
// http://kevin.vanzonneveld.net | |
// + original by: Waldo Malqui Silva | |
// + input by: Steve Hilder | |
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) | |
// + revised by: gorthaur | |
return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) ); | |
} | |
let low = 0, high = arr.length, index = halfway(low, high) | |
while(low !== high || strcmp(q, arr[index]) === 0) { | |
if (strcmp(q, arr[index]) === 0) { | |
return index | |
} | |
else if (strcmp(q, arr[index]) === 1) { | |
low = index + 1 | |
index = halfway(low, high) | |
continue | |
} | |
else { | |
high = index - 1 | |
index = halfway(low, high) | |
continue | |
} | |
} | |
return null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment