0

The objective is to return the index of an element in a string array if present. The method uses a basic binary search using compareTo statements. With more than two elements in a tested array, the method will not detect the present element and return -1. The Java code this question is referring to is below. How do I make the binary search method work as intended?

   public static int binarySearch(String[] array, String x) {
        int high = array.length - 1;
        int low = 0;

        while (low <= high) {

            int mid = low + (high - low) / 2;

            if (x.compareTo(array[mid]) == 0) {
                return mid;
            }
            if (x.compareTo(array[mid]) > 0) {
                low = mid + 1;
            }
            else {
                high = mid - 1;
            }
        }
        return -1;
    }
Matt
  • 7
  • 1
  • Can you post your test data ? – Kai-Sheng Yang Apr 13 '22 at 16:18
  • It works. I tested your method with the following code: `System.out.println(binarySearch(new String[] { "a", "b", "c" }, "a")); System.out.println(binarySearch(new String[] { "a", "b", "c" }, "b")); System.out.println(binarySearch(new String[] { "a", "b", "c" }, "c"));` – ubw Apr 13 '22 at 16:20

1 Answers1

0

add an extra variable and set it to -1;

int loc=-1;

change the code

int mid=low+(high-low)/2;

to

 int mid=(low+high)/2;
 if(x.compareTo(array[mid]==0)
 {
  loc=mid;
  break;
 }
 else if(x<array[mid])
 {
  last=mid-1;
 }
 else
 {
   low=mid+1;
 }

then

if(loc>=0)
{
 System.out.println(loc+1);
} 
else
{
  System.out.println("no element");
}
Daksh Rawal
  • 238
  • 2
  • 13