Java BinarySearch

前端之家收集整理的这篇文章主要介绍了Java BinarySearch前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我能得到一些帮助吗?我已经尝试了很多方法来使这个工作我得到数组排序和打印但之后我的二进制搜索功能不想运行并给我正确的结果.它总是给我-1.有帮助吗?
public class BinarySearch {
public static final int NOT_FOUND = -1;
public static int binarySearch(double[] a,double key) {
    int low = 0;
    int high = a.length -1;
    int mid;
    while (low<=high) {
        mid = (low+high) /2;
        if (mid > key) 
            high = mid -1;
        else if (mid < key) 
            low = mid +1;
        else 
            return mid;
    }
    return NOT_FOUND;
}
public static void main(String[] args) {
    double key = 10.5,index;
    double a[] ={10,5,4,10.5,30.5};
    int i;
    int l = a.length;
    int j;
    System.out.println("The array currently looks like");
    for (i=0; i<a.length; i++)
        System.out.println(a[i]);
    System.out.println("The array after sorting looks like");
    for (j=1; j < l; j++) {
        for (i=0; i < l-j; i++) {
            if (a[i] > a[i+1]) {
                double temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
            }
        }
    }
    for (i=0;i < l;i++) {
        System.out.println(a[i]);
    }
    System.out.println("Found " + key + " at " + binarySearch(double a[],key));
}   
}

解决方法

你实际上并没有与数组值进行比较.在
while (low <= high) {
      mid = (low + high) / 2;
      if (mid > key) {
          high = mid - 1;
      } else if (mid < key) {
          low = mid + 1;
      } else {
          return mid;
      }
}

而是使用此部分

while (low <= high) {
        mid = (low + high) / 2;
        if (a[mid] > key) {
            high = mid - 1;
        } else if (a[mid] < key) {
            low = mid + 1;
        } else {
            return mid;
        }
    }

你找对索引是正确的,但你所做的是你只是将索引号与你的密钥进行比较,这显然是不正确的.当您编写[mid]时,您实际上会将您的密钥与索引中间的数字进行比较.

最后一行代码也是编译错误,应该是

System.out.println("Found " + key + " at " + binarySearch(a,key));
原文链接:https://www.f2er.com/java/127376.html

猜你在找的Java相关文章