Nicoji_
Nicoji_

Reputation: 77

My recursive function (javascript) always return false, even when it's true

I have an issue with a recursive function. It always return false, even when it's true.

I have the following array with names :

const tableaux = ["Nico","Luc","Paul","Jean","Samy",
"Domi","Cricri","André","Valérie","Mouss","Léon",
"Lionnel","Jacques","Marie","Vanessa","Mohammed","Fatou"];

And here is my function :

tableaux.sort(); 

const binarySearch = (array, nameToFind, start, end) => { 
    
    if(start > end) {
        return false;
    }

    let mid = Math.floor((start + end) / 2); 
    
    if(mid === nameToFind) {
        return true;
    }

    if(nameToFind < tableaux[mid]) {
        return binarySearch(array, nameToFind, start, mid - 1); 
    } else {
        return binarySearch(array, nameToFind, mid + 1, end);
    }
}

Then when i use a name that is in my array, it still return false :

let test = binarySearch(tableaux, 'Marie', 1, 17);

console.log(test);

Upvotes: 0

Views: 171

Answers (1)

coreyward
coreyward

Reputation: 80110

You are doing the following:

let mid = Math.floor((start + end) / 2); 

if (mid === nameToFind) {
  return true;
}

In this, you assign mid a number (the index you're looking for), and then compare that directly with nameToFind. You just need to compare against the item at the index mid instead:

let mid = Math.floor((start + end) / 2); 

if (array[mid] === nameToFind) {
  return true;
}

Upvotes: 1

Related Questions