Skip to content

Instantly share code, notes, and snippets.

@clarketm
Last active April 8, 2017 06:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clarketm/7682eb7464e5c8df02958373607af1fa to your computer and use it in GitHub Desktop.
Save clarketm/7682eb7464e5c8df02958373607af1fa to your computer and use it in GitHub Desktop.
Binary Search (JavaScript)
function binarySearch(array, target) {
var startIndex = 0,
stopIndex = array.length - 1,
middle,
count = 0;
while (startIndex < stopIndex) {
count++;
middle = ~~((stopIndex + startIndex) / 2);
// adjust search area
if (target < array[middle]) {
stopIndex = middle - 1;
} else if (target > array[middle]) {
startIndex = middle + 1;
} else {
break; // target is found (or list is exausted)
}
}
// # of iterations
console.log(count + " iterations");
//make sure it's the right value
return (array[middle] === target) ? middle : -1;
}
var array = ["a", "b", "c", "d", "e", "f", "h", "i", "j"];
console.log(binarySearch(array, "i")); // 7 found //=> 3 iterations
console.log(binarySearch(array, "b")); // 1 found //=> 2 iterations
console.log(binarySearch(array, "g")); // -1 not found //=> 2 iterations
@oky1
Copy link

oky1 commented Apr 8, 2017

stopIndex = array.length - 1 not searching last index of array
first index too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment