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.
Analysis:
1. if target==A[mid], return.
2. if left is in order, then determine whether target fits into that specific range or not.
3. if right is in order, then similarly, determine whether target fits into the range or not.
public class Solution {
public int search(int[] A, int target) {
int low=0, high=A.length-1;
while(low <= high) {
int mid = (low+high)/2;
if(target==A[mid]) return mid;
if(A[mid] >= A[low]) { // left in order
if(target<A[mid] && target>=A[low]) high=mid-1;
else low=mid+1;
}
if(A[mid] <= A[high]) { // right in order
if(target>A[mid] && target<=A[high]) low=mid+1;
else high=mid-1;
}
}
return -1;
}
}