Recursive binary search method having only 2 arguments

孤者浪人 提交于 2019-12-21 09:36:52

问题


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.


回答1:


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:


Cache and test the result of the function call, if -1 return, else calculate and return.




回答3:


You can check if the result of the recursive binarySearch call in that block is -1 before you add the indexes:

else if(key.compareTo(cards.get(mid)) > 0){
    result = binarySearch(cards.subList(mid + 1, cards.size()), key);
    if (result >= 0) {
        return mid + 1 + result;
    } 
    return -1;
}


来源:https://stackoverflow.com/questions/8392637/recursive-binary-search-method-having-only-2-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!