二进制搜索不适用于双打

问题描述 投票:3回答:2

此程序与整数非常有效,但对双精度不是很好。没有错误,但是程序返回-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));
  }
}
java search binary
2个回答
6
投票

您应更改条件:

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

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

还请注意,为了使这项工作有效,必须对数组进行排序(这是binary search的全部内容),可以使用Arrays#sort

Arrays#sort

我建议您重命名您的类,使其以大写字母开头(遵循Java命名约定)。


2
投票

正如@tobias_k指出:

为了使二进制搜索起作用,您需要先对数组进行排序。有关详细信息,请参见Arrays.sort(a);

© www.soinside.com 2019 - 2024. All rights reserved.