仅具有2个参数的递归二进制搜索方法 [英] Recursive binary search method having only 2 arguments
问题描述
好的,这是给学校做的作业.我进行递归二进制搜索没有问题,但是赋值明确表示该方法应仅包含2个参数,列表和要搜索的项目.这是我有点迷路的地方.
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;
}
因此,除非我搜索不存在的东西并且它属于列表的上半部分,否则这将正常工作.因为我只传递2个参数,所以每次递归调用都必须更改列表,但是,如果它位于上半部分,则我不会丢失索引点,因此如果递归调用,则必须在其上添加索引它最终不在上半部分,然后返回-1 +我以前考虑的所有那些索引.有什么办法可以清除所有内容并使它返回-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.
推荐答案
您可以使用两种方法,其中一种调用另一种方法. public方法公开您的家庭作业需要的两个参数接口.它还可以检查空参数-这种东西一开始就只需要检查一次.
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.
这篇关于仅具有2个参数的递归二进制搜索方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!