Created
January 10, 2020 06:41
-
-
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.
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
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