简体   繁体   English

如何在没有 break 语句的情况下键入 BinarySearch 方法 while-loop?

[英]How to type a BinarySearch method while-loop without break statement?

I just finished studying the simple BinarySearch algorithm, but one thing that bugs me is that I was taught that break (and continue) statements are often redundant in Java and you can do with most while-loops without them.我刚刚完成了简单的 BinarySearch 算法的学习,但让我感到困扰的一件事是,我被告知 break(和 continue)语句在 Java 中通常是多余的,并且您可以在没有它们的情况下使用大多数 while 循环。 But I can't figure out how to get rid of hem from the BinarySearch while-loop below:-但我无法弄清楚如何从下面的 BinarySearch while-loop 中摆脱下摆:-

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");
    }
}

Question 1: Why does the loop keeps going on and on if I didn't include the break statement?问题 1:如果我不包含 break 语句,为什么循环会一直继续下去? Shouldn't the variable "lo" eventually become greater than "hi"?变量“lo”最终不应该大于“hi”吗? How come the last if- conditional can see that, but not the while-loop-conditional?为什么最后一个 if-conditional 可以看到,而 while-loop-conditional 却看不到?

Question 2: How can I can type the while-loop without needing the break statement?问题 2:如何在不需要 break 语句的情况下输入 while 循环?

The basic strategy is to add extra conditions to the loop, and set and use these conditions in the code within the loop.基本策略是在循环中添加额外的条件,并在循环内的代码中设置和使用这些条件。

For example, for the above loop:例如,对于上面的循环:

int keyIndex = -1;

. . .

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

However, using a break statement for loops such as this is considered an acceptable programming practice by many developers.然而,对于诸如此类的循环使用 break 语句被许多开发人员认为是一种可接受的编程实践。

Here is a reddit discussion on the use of break and continue .这是关于使用 break 和 continuereddit 讨论

And here is a question in the sister site on software engineering .这是姊妹网站上关于软件工程的一个问题

As to why your loop does not exit without the break statement is if the key is found, the value of lo is not changed.至于为什么你的循环在没有 break 语句的情况下不退出是如果找到了键, lo的值不会改变。 So no, the value of lo does not necessarily become greater than high .所以不, lo的值不一定大于high

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM