Skip to content

Instantly share code, notes, and snippets.

@YozhEzhi
Created April 8, 2017 21:02
Show Gist options
  • Save YozhEzhi/ce4b5e4cbc94938523a0cc6ac1414131 to your computer and use it in GitHub Desktop.
Save YozhEzhi/ce4b5e4cbc94938523a0cc6ac1414131 to your computer and use it in GitHub Desktop.
Binary search
function binarySearch(list, item) {
let low = 0;
let high = list.length - 1;
while(low <= high) {
let mid = Math.floor((low + high) / 2);
let guess = list[mid];
if (guess === item) return guess;
if (guess > item) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return null;
}
const arr = [1, 3, 5, 7, 9];
console.log(binarySearch(arr, 7)); // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment