Search code examples
javaarraylistbinary-search

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


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


Solution

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