Last active
October 19, 2017 18:12
-
-
Save Spuffynism/69b3b73ac7388139cc9e2f1a2e4efc96 to your computer and use it in GitHub Desktop.
JS binary search
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
var binarySearch = function (a, x) { | |
var low = 0, | |
high = a.length - 1, | |
mid; | |
while (low <= high) { | |
mid = Math.floor((low + high) / 2); | |
if (a[mid] < x) | |
low = mid + 1; | |
else if (a[mid] > x) | |
high = mid - 1; | |
else | |
return "found " + x + " at [" + mid + "]"; | |
} | |
return -1; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment