二进制搜索发现索引不正确

时间:2013-03-01 20:36:38

标签: java binary-search

我将此代码用于二进制搜索。

public class BinarySearch {

private static int location;
private static int a = 14;
static int[] numbers = new int[]{3, 6, 7, 11, 14, 16, 20, 45, 68, 79};

public static int B_Search(int[] sortedArray, int key) {
    int lowB = 0;
    int upB = sortedArray.length;
    int mid;
    while (lowB < upB) {
        mid = (lowB + upB) / 2;

        if (key < sortedArray[mid]) {
            upB = mid - 1;
        } else if (key > sortedArray[mid]) {
            lowB = mid + 1;
        } else {
            return mid;
        }
    }
    return -1;
}

public static void main(String[] args) {
    BinarySearch bs = new BinarySearch();
   location= bs.B_Search(numbers, a);
   if(location != -1){
       System.out.println("Find , at index of: "+ location);
   }
   else{
       System.out.println("Not found!");
   }
}
}

输出:

α= 14  没找到!!

为什么?

1 个答案:

答案 0 :(得分:9)

  

输出:a = 68未找到!!为什么呢?

二进制搜索算法依赖于要开始排序的输入。它假设如果它找到一个大于目标值的值,这意味着它需要在输入中更早看(反之亦然)。

您的数组未排序:

static int[] numbers = new int[]{6, 3, 7, 19, 25, 8, 14, 68, 20, 48, 79};

将它排序为开始,它应该没问题。