Tell us what’s happening:
Describe your issue in detail here.
Recursive Function and return flow of programming is very beautiful. I never thought return has that many depth and complicated untill I used with recursive function.
Although I solved the Binary Search problem with some work around. But I want to learn the flow of return statement in recursive statement and how can I overcome the following code issues. which is instead of returning “value not found” its returning items in arrayPath.
Please, anyone if known answer in details not in one line.
Your code so far
function binarySearch(searchList, value,arr) {
let arrayPath =arr;
let mid= Math.floor((searchList.length-1)/2)
arrayPath.push(searchList[mid])
if(searchList.length-1>0){
if(searchList[mid]==value){
return arrayPath;
}
else if(searchList[mid]>value){
binarySearch(searchList.slice(0,mid),value,arrayPath);
}
else {
binarySearch(searchList.slice(mid+1),value,arrayPath);
}
}else{
return arrayPath = 'Value Not Found';
}
return arrayPath;
}
const testArray = [
0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 49, 70
];
console.log(binarySearch(testArray,6,[]));
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36
Challenge: Algorithms - Implement Binary Search
Link to the challenge: