Skip to content

Instantly share code, notes, and snippets.

@lexcraw4d
Created July 14, 2021 05:01
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lexcraw4d/0543a13b5b14565654d85ffe1241b399 to your computer and use it in GitHub Desktop.
Binary Search Algorithm
const data = [12, 23, 38, 40, 54, 62, 71, 87, 99];
const binarySearch = (arr, num, left, right) => {
let middle = Math.floor((left + right) / 2);
// range overlapped, so never found number
if (left > right) {
return -1;
}
else if (num === arr[middle]) {
return middle;
}
else if (num < arr[middle]) {
// call again with a new right value
return binarySearch(arr, num, left, middle - 1);
}
else {
// call again with a new left value
return binarySearch(arr, num, middle + 1, right);
}
};
// set initial left and right values on first call
console.log(binarySearch(data, 12, 0, data.length - 1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment