Last active
April 8, 2017 06:01
-
-
Save clarketm/7682eb7464e5c8df02958373607af1fa to your computer and use it in GitHub Desktop.
Binary Search (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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
stopIndex = array.length - 1 not searching last index of array
first index too