Java BinarySearch [英] Java BinarySearch

查看:168
本文介绍了Java BinarySearch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能得到一些帮助吗?我已经尝试了很多方法来使这个工作我得到数组排序和打印但之后我的二进制搜索功能不想运行并给我正确的结果。它总是给我-1。有什么帮助吗?

Can I get some help please? I have tried many methods to get this to work i got the array sorted and to print but after that my binary search function doesnt want to run and give me right results. It always gives me -1. Any help?

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


推荐答案

你实际上并没有与数组值进行比较。 in

you are not actually comparing with the array values. in

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

你找对索引是正确的,但你是什么正在做的是你只是将索引号与你的密钥进行比较,这显然是不正确的。当您写 a [mid] 时,您实际上会将您的密钥与索引 mid 的数字进行比较。

You were correct to find the indexes, but what you were doing is that you were just comparing index number with your key, which is obviously incorrect. When you write a[mid] you will actually compare your key with the number which is at index mid.

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

Also the last line of code is giving compile error, it should be

System.out.println("Found " + key + " at " + binarySearch(a, key));

这篇关于Java BinarySearch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆