0

I just learned about Arrays and came to know about Linear and Binary Search . Is it possible to perform Binary Search on String Array ? I tryed to achieve but failed

here while running the code output is NOT FOUND ; I just can't get it.

String a[] = {"Dossa" , "Maggie" , "Chai" , "Coffe"};
String key = "Coffe";
int index = hwq(a , key);
if(index == -1 ){
    System.out.print("NOT FOUND ");
}else{
    System.out.print(key + " is at index = " + index);
}
}

public static int hwq(String a[] , String key){
    int start = 0 , end = a.length - 1;
    while(start <= end){
        int mid = ( start + end)/2 ;
        if(a[mid] == key ){
            return mid ;
        }
        start ++;
        end --;
    }
    return -1;
}

It would be helpful to know my mistake and also a new or different apporoach to this problem.

  • You have two other problems apart from the string comparison problem. (1) binary search requires that the array be in order. (2) each successive pass needs to reduce the search space by half, by selecting either the part that's below the midpoint or the part that's above the midpoint. What you've got looks at the same middle element over and over again, so it's not actually any kind of search. – undefined symbol Feb 20 '23 at 03:04
  • So I think Binary Search is not Possible for String Array , as in my code if I change my logic (int mid = start ++;) I will get the result but it will be Liner Search Not BInary is it? – Devesh Singh Feb 21 '23 at 03:41
  • Of course binary search is possible; it's just that (1) what you've coded is not binary search, and (2) as noted in the closure reason, your string comparisons are wrong. – undefined symbol Feb 21 '23 at 13:18

0 Answers0