Skip to content

Instantly share code, notes, and snippets.

@Spuffynism
Last active October 19, 2017 18:12
Show Gist options
  • Save Spuffynism/69b3b73ac7388139cc9e2f1a2e4efc96 to your computer and use it in GitHub Desktop.
Save Spuffynism/69b3b73ac7388139cc9e2f1a2e4efc96 to your computer and use it in GitHub Desktop.
JS binary search
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