Okay so this is for a school assignment. I have had no problems doing a recursive binary search but the assignment specifically says that the method should only take 2 arguments, the list, and the item you are searching for. This is where I am getting a little lost.
public int binarySearch(List<Card> cards, Card key)
{
int mid = (cards.size()) / 2;
if(cards.size() == 1) {
if(key.equals(cards.get(0))) {
return 0;
}
}
else {
if(key.equals(cards.get(mid))) {
return mid;
}
else if(key.compareTo(cards.get(mid)) == - 1) {
return binarySearch(cards.subList(0, mid), key);
}
else if(key.compareTo(cards.get(mid)) == 1) {
return mid + 1 + binarySearch(cards.subList(mid + 1, cards.size()), key);
}
}
return -1;
}
So this will work fine unless I am searching for something that doesn't exist and it belongs in the upper half of the list. Because I am only passing through 2 arguments, I have to change the list with each recursive call, however, if it's in the upper half i can't lose my index spot so I have to add those on there with the recursive call, if it ends up not being in the upper half then it returns -1 + all those indexes i was accounting for previously. Is there a way I can clear it all out and make it just return -1? Any advise is appreciated.
Cache and test the result of the function call, if -1 return, else calculate and return.
You can check if the result of the recursive binarySearch call in that block is -1 before you add the indexes:
You could use two methods, where one calls the other. The public method exposes the two parameter interface your homework needs. It can also check for null parameters - the sort of things that only need checking once, right at the beginning.
Your second method is private and is only called from inside your first method. That is your standard recursive binary search, with as many parameters as you need.