英文:
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<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);
}
}
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论