[LeetCode] Search in Rotated Sorted Array (Java)

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.


Take “4 5 6 7 0 1 2” as an example. The mid entry is 7. We can compare it with the first entry. If the first entry is smaller than the mid entry, then the first half (from 4 to 7) must be in strictly increasing order. So we can compare target with the first entry and the mid entry, then we can decide if the target is in this half or not. If the first entry is larger than the mid entry, then the second half (fron 7 to 2) is in strictly increasing order. We can compare the target with them. Using this algorithm, every time we can throw half of the array.



The complexity is O(log n), which is similar to binary search.

Follow up

Find the rotation pivot.

Solution from leetcode.com.

For details, visit http://leetcode.com/2010/04/searching-element-in-rotated-array.html.