Java – binary search is not applicable to doubles

This program applies to integers, but not doubles There was no error, but the program returned - 1 Sorry, if this is a stupid question, but I'm new to programming

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

Solution

You should change the conditions:

If (arr [mid] > x) should be if (arr [mid] < x), otherwise if (arr [mid] < x) should be (arr [mid] > x)

Also note that in order for this to work, the array must be sorted (this is all the points of binary search). You can use arrays #sort:

Arrays.sort(a);

In addition, I recommend that you rename the class to uppercase (following the Java Naming Convention)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>