java - 二进制搜索未排序的数组

标签 java arrays binary-search

希望有人知道这个 Java 认证问题的答案:

public static void main(String[] args) {
 String[] sa = {"d", "c", "a", "b" };
 int x = Arrays.binarySearch(sa, "b");
 Arrays.sort(sa);
 int y = Arrays.binarySearch(sa, "b");
 System.out.println(x + " " + y);
}

哪两个结果是可能的? (选择两项。)
一)7 0
B) 7 1
C) 7 3
D) -1 0
E) -1 1
F) -1 3

唯一正确的答案是 E) -1 1,因为如果你玩二分搜索算法,这是唯一可能的输出。但他们要我选择两个... 所以第二个必须是 B) 7 1,因为排序数组中的第二个 binarySearch 将始终返回 1

所以我的问题是,为什么 B) 7 1 是一个可能的结果? 更具体地说:未排序数组中的第一个 binarySearch 怎么可能返回 7?

提前致谢

最佳答案

这是一个有技巧的问题。根据文档,对未排序数组进行二分查找的结果是未定义的:

The array must be sorted (as by the sort method, above) prior to making this call. If it is not sorted, the results are undefined.

这特别意味着任何数字,包括七,都是公平的游戏。

排序后的结果是明确定义的:您将得到 1。就像魔术一样,答案列表中只有两对以 1 结尾,所以 BE 是考官的选择期待你做出。

关于java - 二进制搜索未排序的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11061314/

相关文章:

javascript - 在 Jquery 中查找字母数字字符串数组中的最大数字

c# - 将值插入数组的有效方法?

Ruby:根据任意数字列表将数字舍入到最接近的数字

java - 如何使用 `Collections.binarySearch()` 通过对象的 ArrayList 进行二分搜索?

java - 如何使用FirefoxProfile通过Firefox浏览器自动下载?

java - 仅比较两个实例之间的一个变量

java - 为什么颜色的深浅会改变?

javascript - 将 Crashlytics 集成到 React Native - Android

python - pandas 中非唯一索引的性能影响是什么?

java - 二分查找的比较次数