Skip to content

Instantly share code, notes, and snippets.

@Nilesh-Saini-09
Created June 19, 2022 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nilesh-Saini-09/853a2dcb5e89ee7d36d3dda89c2547bf to your computer and use it in GitHub Desktop.
Save Nilesh-Saini-09/853a2dcb5e89ee7d36d3dda89c2547bf to your computer and use it in GitHub Desktop.
Recursive Binary Search
// ES6 Arrow Function
const binarySearch = (arr, k) => {
let start = 0, end = arr.length - 1, mid;
mid = Math.floor((start + end) / 2);
if(arr.length === 1 && arr[0] === k) return -1;
if(arr[mid] === k) return mid;
if(arr[mid] > k) {
return binarySearch(arr.slice(0, mid), k);
} else {
return binarySearch(arr.slice(mid));
}
}
// let testArray = [1, 2, 3, 4, 5, 6, 7, 8];
// let x = 8;
// binarySearch(testArray, x);
// output => 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment