Logic Error: Binary search fails with more than two elements in a string array

Logic Error: Binary search fails with more than two elements in a string array

objective 是 return 字符串数组中元素的索引(如果存在)。该方法使用使用 compareTo 语句的基本二进制搜索。如果测试数组中有两个以上的元素,该方法将不会检测当前元素和 return -1。这个问题所指的 Java 代码如下。如何使二进制搜索方法按预期工作?

   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;
    }

添加一个额外的变量并将其设置为-1;

int loc=-1;

更改代码

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

 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;
 }

然后

if(loc>=0)
{
 System.out.println(loc+1);
} 
else
{
  System.out.println("no element");
}