Home > Back-end >  function wont return despite condition of the return being true
function wont return despite condition of the return being true

Time:11-03

In a binary search on an array.

private int binarySearch(int first, int last, String name){
    int middle = (first last)/2;

    if (catalogue[middle].getName().equals(name)){
        return catalogue[middle].getNumber();
    }
    else{
        if(catalogue[middle].getName().compareTo(name) < 0){
            binarySearch(middle, last, name);
        }
        else {
            binarySearch(first, middle, name);
        }
    }

    return -1;
}

With each element in the array catalogue being an object Entry with the attribute name and number. binarySearch should find the Entry with the same name and return the number of that Entry.

For some reason

if (catalogue[middle].getName().equals(name)){
    return catalogue[middle].getNumber();
}

The method will only return -1 despite seemingly reaching the other return statements?

CodePudding user response:

Looks like you should replace < with > and use return from your nested binarySearch() call:

if(catalogue[middle].getName().compareTo(name) > 0)
    return binarySearch(middle, last, name);
return binarySearch(first, middle, name);
  •  Tags:  
  • java
  • Related