Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected output:
2

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading