Can we use binary search with an unsorted array? [duplicate]

99封情书 提交于 2020-08-24 05:09:42

问题


I have an array that looks like

2 6 8 5 34 1 12

Can I use a binary search on some subarray?


回答1:


You can use binary search on only one kind of "unsorted" array - the rotated array.

It can be done in O(log n) time like a typical binary search, but uses an adjusted divide and conquer approach. You can find a discussion about it here.




回答2:


No, binary search needs a sorted array. You might have other properties of an array that enables you to make a search that is more efficient than a mere iteration but the very nature of binary search necessitates sorted data.

If you know that part of your array is sorted you might extract that, of course, execute a binary search there and exclude this from the otherwise linear search.




回答3:


You can't. "Binary search" checks if the value is in left or right side, comparing when it's lesser or bigger than the central item.

Array: 2 6 8 5 34 1 12

Suppose that you want to find '1', so in first iteration the method will compare '1' with the currently central element (in this case '5'). The method would say: "As 1 is lesser than 5, I'm going to search in left side", but if we do this, we will never find it, because at left side there aren't one's.

But if we have: 1 2 5 6 8 12 34

Note that 1 is lesser than 6 (the central element), so in the next step, the algorithm will continue searching in left side and that's OK. So, to use "Binary Search" the elements MUST BE sorted.



来源:https://stackoverflow.com/questions/35895627/can-we-use-binary-search-with-an-unsorted-array

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