binary search found index is incorrect

会有一股神秘感。 提交于 2020-01-17 13:42:24

问题


I have this code to 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!");
   }
}
}

output:

a=14 not Found!!

Why?


回答1:


output: a=68 not Found!! Why?

The binary search algorithm relies on the input being sorted to start with. It assumes that if it finds a value which is greater than the target one, that means it needs to look earlier in the input (and vice versa).

Your array isn't sorted:

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

Sort it to start with, and it should be fine.



来源:https://stackoverflow.com/questions/15166453/binary-search-found-index-is-incorrect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!