Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created July 11, 2022 01:56
Show Gist options
  • Save CarlaTeo/5a13bd807889e5fce092aad35237a0ef to your computer and use it in GitHub Desktop.
Save CarlaTeo/5a13bd807889e5fce092aad35237a0ef to your computer and use it in GitHub Desktop.
function binarySearch(array, value) {
let i = 0;
let j = array.length - 1;
while(i <= j) {
const middle = Math.floor((j + i) / 2);
if(array[middle] === value) return middle;
if(array[middle] > value) j = middle - 1;
else i = middle + 1;
}
return -1;
}
console.log(binarySearch([3,5,7,10,18], 10)); // 3
console.log(binarySearch([3,5,7,10,18], 0)); // -1
console.log(binarySearch([3,5,7,10,18], 5)); // 2
console.log(binarySearch([], 10)); // -1
console.log(binarySearch([10], 10)); // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment