【问题标题】:How to type a BinarySearch method while-loop without break statement?如何在没有 break 语句的情况下键入 BinarySearch 方法 while-loop?
【发布时间】:2019-11-04 13:39:50
【问题描述】:

我刚刚完成了简单的 BinarySearch 算法的学习,但让我感到困扰的一件事是,我被告知 break(和 continue)语句在 Java 中通常是多余的,并且您可以在没有它们的情况下使用大多数 while 循环。但我不知道如何从下面的 BinarySearch 循环中摆脱下摆:-

public static void BinarySearch(int[] list, int key){
int lo = 0;
int hi = list.length-1;
int mid = 0;
while(lo<=hi){
    mid = lo + (hi-lo) / 2;
    if(key<list[mid])
        hi = mid-1;
    else if(key>list[mid])
        lo = mid+1;
    else {
        System.out.println("Key is found at index = " + mid);
        break;
    }
    if(lo>hi){
        System.out.println("Key doesn't exist in the list");
    }
}

问题 1:如果我没有包含 break 语句,为什么循环会一直持续下去?变量“lo”不应该最终变得大于“hi”吗?为什么最后一个 if-conditional 可以看到,而 while-loop-conditional 却看不到?

问题 2:如何在不需要 break 语句的情况下键入 while 循环?

【问题讨论】:

    标签: java while-loop break infinite


    【解决方案1】:

    基本策略是在循环中添加额外的条件,并在循环内的代码中设置和使用这些条件。

    例如,对于上面的循环:

    int keyIndex = -1;
    
    . . .
    
    while ( (lo<=hi) && (keyIndex == -1) ) {
        . . .
        else {
            System.out.println("Key is found at index = " + mid);
            keyIndex = mid;     // <<< 
        }
        . . .
    }
    

    但是,对这样的循环使用 break 语句被许多开发人员认为是可接受的编程实践。

    这是reddit discussion on the use of break and continue

    这是question in the sister site on software engineering

    至于为什么没有break语句你的循环不退出是如果找到键,lo的值没有改变。所以不,lo 的值不一定会大于 high

    【讨论】:

    • 啊,我明白了。还有一个问题。 keyIndex 的新值可以是任意的(任何不是 -1 的),对吧?不过,我可能会坚持打破这样的循环,因为这是它可接受的用法之一。
    • 是的,我使用了 keyIndex,因为二进制搜索通常用于返回一个项目。您也可以使用布尔值。
    猜你喜欢
    • 2019-03-06
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    相关资源
    最近更新 更多