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

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

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

问题

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

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

  1. import java.util.*;
  2. public class Test {
  3. public static void main(String[] args) {
  4. ArrayList<String> bricks = new ArrayList<String>(List.of("BBBB", "BBBB", "CCCC"));
  5. ArrayList<String> bricksNeeded = new ArrayList<String>(List.of("BBBB", "BBBB"));
  6. int nFound = 0;
  7. int index;
  8. for (String brickNeeded : bricksNeeded) {
  9. index = Collections.binarySearch(bricks, brickNeeded);
  10. if (index >= 0) {
  11. bricks.remove(bricks.get(index));
  12. nFound++;
  13. break;
  14. }
  15. }
  16. System.out.println(nFound);
  17. }
  18. }

输出:
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".

  1. import java.util.*;
  2. public class Test{
  3. public static void main(String[] args) {
  4. ArrayList&lt;String&gt; bricks = new ArrayList&lt;String&gt;(List.of(&quot;BBBB&quot;,&quot;BBBB&quot;,&quot;CCCC&quot;));
  5. ArrayList&lt;String&gt; bricksNeeded = new ArrayList&lt;String&gt;(List.of(&quot;BBBB&quot;,&quot;BBBB&quot;));
  6. int nFound = 0;
  7. int index;
  8. for(String brickNeeded:bricksNeeded){
  9. index = Collections.binarySearch(bricks, brickNeeded);
  10. if(index &gt;= 0){
  11. bricks.remove(bricks.get(index));
  12. nFound ++;
  13. break;
  14. }
  15. }
  16. System.out.println(nFound);
  17. }
  18. }

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:

确定