二进制搜索不适用于双打

You*_*zie 3 java binary search

这个程序适用于整数,但不是双打.没有错误,但程序返回-1.对不起,如果这是一个愚蠢的问题,但我是编程的新手.

public class binarySearchProject
{
  public static int binarySearch(double[] arr, double x, int high, int low)
  {
    int mid=(high+low)/2;
    if(high==low || low==mid || high==mid)
    {
      return -1;
    }
    if(arr[mid]>x)
    {
      return binarySearch(arr, x, high, mid);
    }
    else if(arr[mid]<x)
    {
      return binarySearch(arr, x, mid, low);
    }
    else if(arr[mid]==x)
    {
      return mid;
    }
    return -1;
  }
  public static void main(String args[])
  {
    double i = 45.3;
    double[] a = {-3, 10, 5, 24, 45.3, 10.5};
    int size = a.length;
    System.out.println(binarySearch(a, i, size, 0));
  }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*oun 5

你应该改变条件:

if(arr[mid]>x) 应该 if(arr[mid]<x)

else if(arr[mid]<x) 应该 else if(arr[mid]>x)

另请注意,为了使这项工作,必须对数组进行排序(这是二进制搜索的全部要点),您可以使用Arrays#sort:

Arrays.sort(a);
Run Code Online (Sandbox Code Playgroud)

另外,我建议您将类重命名为大写(遵循Java命名约定).