Binarysearch unsorted array

梦想与她 提交于 2019-12-01 12:08:14

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.

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.

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