Skip to content

Instantly share code, notes, and snippets.

@tdubs42
Created February 20, 2024 00:45
Show Gist options
  • Save tdubs42/5f9233f98393f9b7cbbe9eebc025cd15 to your computer and use it in GitHub Desktop.
Save tdubs42/5f9233f98393f9b7cbbe9eebc025cd15 to your computer and use it in GitHub Desktop.
Binary Search Function for Sorted List - JavaScript
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;
}
module.exports = binarySearch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment