问题
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