Search code examples
javaarraysbinary-search

Working Sturcture of Arrays. binarySearch() method in java


I'm trying solve problem in Strings,finding matching characters in to String. I solve it using Character Array and inner loop but i think it has more time complexity. so try to solve it in Arrays binary search but it gives inappropriate result.i want working structure of binary search method in java.

I set matched value in the String two to duplicate char '#',because don't want to match another char.

public static void main(String[] args) {

        Scanner s= new Scanner(System.in);


        String team1 = s.next();
        String team2 = s.next();

        char[] teamA = team1.toCharArray();
        char[] teamB = team2.toCharArray();

        Arrays.sort(teamB);

        int count = 0;
        for(int a=0;a< teamA.length;a++) {
            int index = Arrays.binarySearch(teamB, teamA[a]);

            if(index >= 0) {
                count++;
                teamB[index] = '#';
            }
        }
        System.out.println(count);
    }

if i give input of two strings "aabc" and "zbaa" expected output is 3 but my program gives output 2.


Solution

  • The problem is that once you update the teamB array in the loop the array is no longer sorted. And in unsorted array binary search will give unexpected outputs.