Skip to content

Instantly share code, notes, and snippets.

@heyitsnovi
Created January 10, 2020 06:41
Show Gist options
  • Save heyitsnovi/901cd6dca8b74ef3846aa6022d49dd9d to your computer and use it in GitHub Desktop.
Save heyitsnovi/901cd6dca8b74ef3846aa6022d49dd9d to your computer and use it in GitHub Desktop.
Recursion is a way where we repeatedly call the same function until a base condition is matched to end the recursion. Proceeding with the steps in method 1 here we use the same idea by just changing the parameters of the function in recursive manner and breaking down the problem.
function binarySearch(arr = [], b_start, b_end, x){
if (b_end < b_start)
return false;
var mid = Math.floor((b_end + b_start)/2);
if (arr[mid] == x) {
return true;
}else if (arr[mid] > x) {
// call binarySearch on [start, mid - 1]
return binarySearch(arr, b_start, mid - 1, x);
}
else {
// call binarySearch on [mid + 1, end]
return binarySearch(arr, mid + 1, b_end, x);
}
}
var array_set = [1, 2, 3, 4, 5,6];
var val_search = 36;
if(binarySearch(array_set, 0, (array_set.length) - 1, val_search) == true) {
console.log(val_search+" Exists");
}else{
console.log(val_search+" Not Exists");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment