Binarysearch unsorted array

自闭症网瘾萝莉.ら 提交于 2019-12-01 10:38:17

问题


Hopefully someone knows the answer to this Java-Certification question:

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

Which two results are possible? (Choose two.)
A) 7 0
B) 7 1
C) 7 3
D) -1 0
E) -1 1
F) -1 3

The only true answer is E) -1 1, because if you play through the binary-search-algorithm this is the only possible output. But they want me to choose two... So the second one have to be B) 7 1 then, because the second binarySearch in the sorted array will always return 1.

So my Question is, why is B) 7 1 a possible result? More specific: How is it possible, that the first binarySearch in the unsorted array returns 7?

Thanks in advance


回答1:


This is a trick question. The results of binary search on an unsorted array are undefined, as per documentation:

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.

This means in particular that any number, including seven, is fair game.

The results on a sorted one are well-defined: you'll get a 1. As if by magic, there are only two pairs that end in 1 on the list of answers, so B and E is the choice the examiners expect you to make.




回答2:


You are probably supposed to stick to the documentation, not to your knowledge of how binary search works in general. The API docs are pretty clear on using Array.binarySearch on unsorted arrays: "If it is not sorted, the results are undefined."

In other words, if the array is not sorted, the result is not required to follow any rules. From the implementation of binary search you may know that the result cannot exceed the array length. However, that's implementation detail. You cannot rely on that.



来源:https://stackoverflow.com/questions/11061314/binarysearch-unsorted-array

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