Skip to content

Instantly share code, notes, and snippets.

@abenteuerzeit
Forked from codecademydev/index.js
Created August 17, 2023 16:23
Show Gist options
  • Save abenteuerzeit/9e8ce085ce10ec25c8568eb0e97195d2 to your computer and use it in GitHub Desktop.
Save abenteuerzeit/9e8ce085ce10ec25c8568eb0e97195d2 to your computer and use it in GitHub Desktop.
Binary Search
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