希望有人知道这个 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
结尾,所以 B
和 E
是考官的选择期待你做出。
关于java - 二进制搜索未排序的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11061314/