Search in Rotated Sorted Array
首先利用二分查找的方法找到最小值,然后在以最小值为分界的两块分别进行二分搜索。
1 int findPos(int A[], int left, int right){ 2 if(left > right) 3 return -1; 4 int mid = (left+right)/2; 5 int result; 6 if(A[left] > A[mid]){ 7 result = findPos(A, left, mid-1); 8 if(result == -1) 9 return mid; 10 else 11 return A[result]<A[mid]?result:mid; 12 } 13 else{ 14 result = findPos(A, mid+1, right); 15 if(result == -1) 16 return left; 17 else 18 return A[left]<A[result]?left:result; 19 } 20 } 21 int bsearch(int A[], int left, int right, int target){ 22 if(left > right) 23 return -1; 24 int mid = (left+right)/2; 25 if(A[mid] == target) 26 return mid; 27 else if(A[mid] < target) 28 return bsearch(A, mid+1, right, target); 29 else 30 return bsearch(A, left, mid-1, target); 31 } 32 int search(int A[], int n, int target) { 33 int pos = findPos(A, 0, n-1); 34 int result = bsearch(A, 0, pos-1, target); 35 if(result != -1) 36 return result; 37 return bsearch(A, pos, n-1, target); 38 }
另外一种方法是直接二分,不过增加了一些判断,比上述代码要简练。
1 int search(int A[], int n, int target) { 2 if(n == 0) 3 return -1; 4 int l = 0, r = n-1, m; 5 while(l <= r){ 6 m = (l+r)/2; 7 if(A[m] == target) 8 return m; 9 else if(A[m] > A[l]){ 10 if(target < A[m] && target >= A[l]) 11 r = m-1; 12 else 13 l = m+1; 14 } 15 else if(A[m] < A[l]){ 16 if(target > A[m] && target <= A[r]) 17 l = m+1; 18 else 19 r = m-1; 20 } 21 else 22 l++; 23 } 24 return -1; 25 }