Skip to content

Instantly share code, notes, and snippets.

@neonux
Created April 11, 2012 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neonux/2359393 to your computer and use it in GitHub Desktop.
Save neonux/2359393 to your computer and use it in GitHub Desktop.
binarySearch compatible with LiveScratchpad v0.3
/*
* This is a JavaScript Scratchpad.
*
* Enter some JavaScript, then Right Click or choose from the Execute Menu:
* 1. Run to evaluate the selected text,
* 2. Inspect to bring up an Object Inspector on the result, or,
* 3. Display to insert the result in a comment after the selection.
*/
function binarySearch(key, array)
{
var low = 0;
var high = array.length - 1;
for (var i = 0; i < 10 && low <= high; ++i) {
var mid = Math.floor(parseInt(low + high) / 2);
var value = array[mid];
if (value < key) {
low = mid + 1;
}
else if (value > key) {
high = 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