2

I wanted something to be returned as output but not able to.

function arrsort(arr){
 return arr.sort(function(a, b){return a - b});
 }
const binarySearch=(arr,num,start,end)=>{
 arr=arrsort(arr);
 start=0;
 end=arr.length;
 var mid = Math.floor(end / 2);
 if (arr[mid] === num) {
    return true;
 } else if (arr[mid] < num && end > 1) {
    binarySearch(arr.splice(mid, Number.MAX_VALUE), num,start,end);
 } else if (arr[mid] > num && end > 1) {
    binarySearch(arr.splice(start, mid), num,start, end);
 } else {
        return false;
 }
  }

I expected the output as true or false.

1
  • This question is similar to: Why does this recursive function return undefined?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Oct 16 at 13:23

1 Answer 1

1

You need some more return statements before calling the same function again.

And while you return for every true if statement, you could omit else.

function arrsort(arr) {
    return arr.sort(function(a, b) {
        return a - b;
    });
}

const binarySearch = (arr, num, start, end) => {
    arr = arrsort(arr);
    start = 0;
    end = arr.length;
    var mid = Math.floor(end / 2);
    if (arr[mid] === num) {
        return true;
    } 
    if (arr[mid] < num && end > 1) {
        return binarySearch(arr.splice(mid, Number.MAX_VALUE), num, start, end);
    } 
    if (arr[mid] > num && end > 1) {
        return binarySearch(arr.splice(start, mid), num, start, end);
    } 
    return false;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.