二进制搜索Java实现算法算法、Java

2023-09-11 02:37:21 作者:午夜的尖叫。

我需要实现二进制搜索算法帮助,可有人告诉我什么是错我的code:

 公众诠释的bsearch(项目idToSearch){
    INT lowerBoundary = 0;
    INT upperBoundary = myStore.size() -  1;
    INT中期= -1;

    而(upperBoundary> = lowerBoundary){
        中期=(lowerBoundary + upperBoundary)/ 2;

        //如果在中间的元素小于被搜索项,比设置为中等新下界
        如果(myStore.get(中间).compareTo(idToSearch)℃,){
            lowerBoundary =中旬 -  1;
        } 其他 {
            upperBoundary =中等+ 1;
        }
    } //结束while循环

    如果(myStore.get(中间).equals(idToSearch)){
        返回中旬;
    } 其他 {
        返回-1; //项目未找到
    }
} // end方法
 

解决方案

我想你犯了一个错误,当更新 lowerBoundary upperBoundary

这可能是:

 如果(myStore.get(MID).compareTo(idToSearch)小于0){
        lowerBoundary =中等+ 1;
    } 其他 {
        upperBoundary =中旬 -  1;
    }
 

和你为什么不打破循环,如果你发现在元素中期

GitHub近10万星 印度小哥用Python和Java实现所有AI算法

I need help with implementing the binary search algorithm, can someone tell me what's wrong with my code:

public int bsearch(Item idToSearch) { 
    int lowerBoundary = 0;
    int upperBoundary = myStore.size() - 1;
    int mid = -1;

    while(upperBoundary >= lowerBoundary) {
        mid = (lowerBoundary + upperBoundary) / 2;

        //if element at middle is less than item to be searched, than set new lower boundary to mid
        if(myStore.get(mid).compareTo(idToSearch) < 0) {
            lowerBoundary = mid - 1;
        } else {
            upperBoundary = mid + 1;
        }
    } //end while loop

    if(myStore.get(mid).equals(idToSearch)) {
        return mid;
    } else {
        return -1; // item not found
    }
} // end method

解决方案

I think you made a mistake when update lowerBoundary and upperBoundary.

It may be:

    if(myStore.get(mid).compareTo(idToSearch) < 0){
        lowerBoundary = mid + 1;
    } else {
        upperBoundary = mid - 1;
    }

And why don't you break the loop if you find the element at mid?