使用数据集进行二进制搜索

时间:2018-04-17 21:40:05

标签: java dataset binary-search

我需要帮助返回其中一组(数据集3)中的特定数据。我在下面的代码中导入了Scanner:

public static int binarySearch(int[] list, int key) {
    int low = 0;
    int high = list.length - 1;

    while (high >= low) {
        int mid = (low + high) / 2;
        if (key < list[mid])
            high = mid - 1;
        else if (key == list[mid])
            return mid;
        else
            low = mid + 1;
    }

    return -low - 1;
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int set = in.nextInt();
    int key = in.nextInt();
    int[][] datasets = { 
            {  },
            {   1,   2,   3,   5,   8,  13,  21,  34,  55, 89 },
            { -81, -72, -63, -54, -45, -36, -27, -18,  -9,  0 },
            {  21,  34,  72, -63,   8,   5, -13, -27, -18,  1,  0,  2 }
    };

    System.out.println("Searching for key " + key + 
                       " in data set "      + set +
                       " returned "         + binarySearch(datasets[set], key));
}

}

我需要返回7 key = 5 set = 3

预期输出:&#34;在数据集3中搜索键5返回7&#34;

当前输出:&#34;在数据集3中搜索键5返回-1&#34;

我还需要返回4 key = 0 set = 3

预期输出:&#34;在数据集3中搜索密钥0返回4&#34;

当前输出:&#34;在数据集3中搜索键0返回-1&#34;

我是否应该在某个地方写一个声明来解决这个问题,或者只是改变数据集3中的数字?

0 个答案:

没有答案