Issue
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?
Solution
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);
Answered By - oleg.cherednik