DEV Community

millidavitti
millidavitti

Posted on

I need help on this: cant get it to work.

// Recursive Binary Search
function recursive(list, target) {
if (list.length === 0) {
return false;
} else {
let midpoint = Math.floor(list.length / 2);
if (list[midpoint] === target) {
return true;
} else {
if (list[midpoint] < target) {
return recursive(list[midpoint + 1], target);
} else {
if (list[midpoint] > target) return recursive(list[midpoint], target);
}
}
}
}

function verifyRecursive(result) {
return Target found : ${result};
}

Discussion (5)

Collapse
benjioe profile image
Benjioe • Edited on

Probably that :

function binarySearch(list, target) {
    if (list.length === 0) {
        return false;
    }

    let midpoint = Math.floor(list.length / 2);
    if (list[midpoint] === target) {
        return true;
    }

    const left = list.slice(midpoint -1);
    const right = list.slice(midpoint +1, list.length);

    return binarySearch(right, target) || binarySearch(left, target);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
millidavitti profile image
millidavitti Author

Thank you for your response. I really appreciate the help

Collapse
nombrekeff profile image
Keff • Edited on

We can't help you like this, please take some time, read the editor guide, and try to compose the question a bit better and you will be more likely to be helped. You can't expect us to do all the job right? ;D

Collapse
joeattardi profile image
Joe Attardi

This is not a good way to ask for help. Simply saying "this does not work" tells us nothing.

  • What is the desired output?
  • What is the actual output?
  • Are there any error messages?
Collapse
millidavitti profile image
millidavitti Author • Edited on

Thank you your response. It returns undefined
and the desire output is a boolean depending on target being present or not