-1

私はこのコードを二分探索に持っています。

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

出力:

a=14が見つかりません!!

なんで?

4

1 に答える 1

9

出力:a=68が見つかりません!! なんで?

二分探索アルゴリズムは、最初にソートされている入力に依存しています。ターゲット値よりも大きい値が見つかった場合、それは入力の早い段階で調べる必要があることを意味します(その逆も同様です)。

配列はソートされていません:

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

最初に並べ替えると、問題ないはずです。

于 2013-03-01T20:37:21.253 に答える