Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created August 17, 2023 16:22
Show Gist options
  • Save codecademydev/13470e4d700883b84ad65b55639bab13 to your computer and use it in GitHub Desktop.
Save codecademydev/13470e4d700883b84ad65b55639bab13 to your computer and use it in GitHub Desktop.
Codecademy export
const binarySearch = (arr, target) => {
let left = 0;
let right = arr.length;
while (right > left) {
const indexToCheck = Math.floor((left + right) / 2);
const checking = arr[indexToCheck];
console.log(indexToCheck);
if (checking === target) {
return indexToCheck;
} else if (checking < target) {
left = indexToCheck + 1;
} else {
right = indexToCheck;
}
}
return null;
}
const searchable = [1, 2, 7, 8, 22, 28, 41, 58, 67, 71, 94];
const target = 41;
targetIndex = binarySearch(searchable, target);
console.log(`The target index is ${targetIndex}.`);
module.exports = binarySearch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment