views:

121

answers:

4

Is there a easy way to search in an array like this? Some examples below :

5 6 7 8 19 45 21 32 40  // Rolled over at 7 th element
15 22 32 45 121 341 40  // Rolled over at 7 th element
1 22 32 45 121 341 400  // Rolled over at 0 th element
+4  A: 

If you're going to do many searches, you could do one pre-processing pass, using linear search, to get the indices of all the rollover places, then do binary search within each section.

But if you're going to search just once I think you have to do linear search. So either way there's a linear search involved.

If you go with the "find rollover first" technique, and you know there's only one rollover point, you can at least bail out of that linear search as soon as you find the point.

mtrw
linear search will be slow! How do I find the rollover point quickly?
javaguy
Sorry, can't think of a way to avoid at least one linear search.
mtrw
+6  A: 

Any algorithm to find "rollover" point would have at least O(n) complexity in worst case.

Imagine, you have sorted array and checked less than n of its elements. For example, if in array 1 2 3 4 5 6 7 8 9 10 you didn't check element 4, I can replace it with 100 and create "rollover" (1 2 3 100 5 6 7 8 9 10). Your algorithm won't know, since it never read this element.

Thus, your only option is to go through all elements until you find rollover.

Thanks to Eyal Schneider for a useful comment.

BTW, am I the only one here who doesn't understand etymology of the word "rollover"?

Nikita Rybak
I think your proof can be made simpler: We know that for every searched number x and sequence S there exist a positions p(S,x) which isn't inspected at all. Define S=1,2,3,..,N, x=2*N. Now build a legal S' by replacing position p(S,x) with 2*N. The algorithm must fail for S or S'.
Eyal Schneider
@Eyal Good idea, thanks. (and you don't really need _x_ if you search for "rollover")
Nikita Rybak
By the way, a slightly different version of the question HAS a logarithmic solution; This happens when the rollover point marks the start/end point of a sorted circular array (e.g. 5,7,10,1,4 but not 5,7,10,8,20)
Eyal Schneider
A: 

Think of your array as a mathematical function, what you want is the local maxima of your function. Although I don't have enough knowledge to explain, you might want to do some research about Hill Climbing. Using some heuristics, you might be able to find your local maxima more efficiently.

Erkan Haspulat
+2  A: 

this should help http://geeksforgeeks.org/?p=1068

bronzebeard