Suppose a sorted array is rotated at some pivot unknown to you beforehand.spa
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).code
You are given a target value to search. If found in the array return its index, otherwise return -1.blog
You may assume no duplicate exists in the array.get
int rotateSearch(int A[], int n, int target){ int begin = 0; int end = n; while(begin < end){ int m = begin + (end - begin)/2; if (A[m] == target) return m; if (A[m] >= A[begin]){ //left longer if (A[begin] <= target && target < A[m]){ //middle left end = m; }else{ begin = m + 1; } }else{ //right longer if (target > A[m] && target <= A[end -1]){ //middle right begin = m + 1; }else{ end = m; } } } return -1; }