二进制搜索Java实现算法 [英] Binary search implementation java algorithm

查看:832
本文介绍了二进制搜索Java实现算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现二进制搜索算法帮助,可有人告诉我什么是错我的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;
    }
 

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

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?

这篇关于二进制搜索Java实现算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆