繁体   English   中英

二进制搜索算法的问题

[英]Prolem with binary search algorithm

最近,我研究了算法,但是发现一个可怕的问题,我无法通过链接中的BinarySearch算法找到数字: http : //algs4.cs.princeton.edu/11model/BinarySearch.java.html

public class BinaryFind {

    public static int indexOf(int[] a, int key) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            // Key is in a[lo..hi] or not present.
            int mid = lo + (hi - lo) / 2;
            if (key < a[mid]) hi = mid - 1;
            else if (key > a[mid]) lo = mid + 1;
            else return mid;
        }
        return -1;
    }


    public static void main(String[] args) {
        int[] a = {1, 4, 56, 4, 3, 7, 8, 2, 66, 45};
        System.out.print(indexOf(a, 7));

    }
}

为什么我找不到数字7?

结果:
在此处输入图片说明

要搜索的数组必须进行排序以使用二进制搜索。

尝试这个:

public static void main(String[] args) {
    int[] a = {1, 4, 56, 4, 3, 7, 8, 2, 66, 45};

    // sort the array
    for (int i = a.length - 1; i > 0; i--) {
        for (int j = 0; j < i; j++) {
            if (a[j] > a[j + 1]) {
                int t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
            }
        }
    }

    System.out.print(indexOf(a, 7));

}

将此行添加到indexOf(..)方法的顶部。

Arrays.sort(a);

这将对您的输入数组进行排序,然后您可以继续查找索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM