Created
September 11, 2012 15:14
-
-
Save egermano/3699567 to your computer and use it in GitHub Desktop.
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
function binSearch(values, target) { | |
return binarySearch(values, target, 0, values.length - 1); | |
}; | |
function binarySearch(values, target, start, end) { | |
if (start > end) { return -1; } //does not exist | |
var middle = Math.floor((start + end) / 2); | |
var value = values[middle]; | |
if (value > target) { return binarySearch(values, target, start, middle-1); } | |
if (value < target) { return binarySearch(values, target, middle+1, end); } | |
return middle; //found! | |
} |
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 result = binSearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 20); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment