为什么二分查找在Java中找不到元素?

huangapple go评论65阅读模式
英文:

Why won't Binary search find an element in Java?

问题

二分查找为什么找不到一个元素?

我有一个包含元素的数组:BBBB,BBBB,CCCC。我想要查找元素BBBB和BBBB。我希望二分查找能找到两个元素,但它只找到一个。输出是“1”,应该是“2”。

import java.util.*;

public class Test {
    public static void main(String[] args) {
        ArrayList<String> bricks = new ArrayList<String>(List.of("BBBB", "BBBB", "CCCC"));
        ArrayList<String> bricksNeeded = new ArrayList<String>(List.of("BBBB", "BBBB"));
        int nFound = 0;
        int index;
        for (String brickNeeded : bricksNeeded) {
            index = Collections.binarySearch(bricks, brickNeeded);
            if (index >= 0) {
                bricks.remove(bricks.get(index));
                nFound++;
                break;
            }
        }
        System.out.println(nFound);
    }
}

输出:
1

预期输出:
2

英文:

Why won't Binary Search find an element?

I have one array with elements: BBBB, BBBB, CCCC. I want to find elements BBBB and BBBB. I want binary search to find two elements and it finds one. The output is "1" and it should be "2".

import java.util.*;

public class Test{
    public static void main(String[] args) {
        ArrayList&lt;String&gt; bricks = new ArrayList&lt;String&gt;(List.of(&quot;BBBB&quot;,&quot;BBBB&quot;,&quot;CCCC&quot;));
        ArrayList&lt;String&gt; bricksNeeded = new ArrayList&lt;String&gt;(List.of(&quot;BBBB&quot;,&quot;BBBB&quot;));
        int nFound = 0;
        int index;
        for(String brickNeeded:bricksNeeded){
            index = Collections.binarySearch(bricks, brickNeeded);
            if(index &gt;= 0){
                bricks.remove(bricks.get(index));
                nFound ++;
                break;
            }
        }
        System.out.println(nFound);
    }
}

Output:
1

Expected output:
2

答案1

得分: 1

你有一个语句 break - 循环将在第一次移除后停止。因此,nFound 只会增加一次。

英文:

You have statement break - loop will be stopped after first removing.
So, nFound will be incremented only once

huangapple
  • 本文由 发表于 2023年6月2日 03:40:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定