Skip to content

Instantly share code, notes, and snippets.

@jharris-code
Created January 24, 2019 01:36
Show Gist options
  • Save jharris-code/6c1c3edd51f4b57c2c9ff8c8ca9a78e7 to your computer and use it in GitHub Desktop.
Save jharris-code/6c1c3edd51f4b57c2c9ff8c8ca9a78e7 to your computer and use it in GitHub Desktop.
Binary Search
function binarySearch(nums, target) {
let start = 0;
let end = nums.length - 1;
let p;
while(start <= end) {
p = Math.floor((start + end) / 2);
if(nums[p] === target) {
return p;
} else {
if(target < nums[p]){
end = p - 1;
} else if (target > nums[p]) {
start = p + 1;
}
}
}
return -1;
}
//outputs: 6
console.log(binarySearch([0,1,3,4,5,6,7,8], 7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment