-
-
Save Nilesh-Saini-09/853a2dcb5e89ee7d36d3dda89c2547bf to your computer and use it in GitHub Desktop.
Recursive Binary Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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