Skip to content

Instantly share code, notes, and snippets.

@YashdalfTheGray
Created May 17, 2016 03:19
Show Gist options
  • Save YashdalfTheGray/ea7a0e9e2ea6fd38a0294b1bd9cd0796 to your computer and use it in GitHub Desktop.
Save YashdalfTheGray/ea7a0e9e2ea6fd38a0294b1bd9cd0796 to your computer and use it in GitHub Desktop.
Binary Search in Javascript
function binarySearch(array, target) {
var min = 0;
var max = array.length-1;
var guess;
while(max >= min) {
guess = Math.floor((max + min)/2);
if(array[guess] === target) {
return target;
} else if (array[guess] < target) {
min = guess + 1;
} else {
max = guess - 1;
}
}
return -1 //solution not found.
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment