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.
Algorithm:
1. This can be done by bisection recursion method, the time complexity would be O(logn).
2. The key point is to see if the pivot of the rotation is on the left of mid point or right.
3. Pay attention to the termination of recursion, 1) when left == right and 2) when A[mid] == target.
4. When do recursion, should make (left, mid), and (mid+1, right). Otherwise, it will go to an endless recursion loop.
My code:
int RSearch(int A[], int left, int right, int target){ if(left == right) { if(A[left] == target) return left; else return -1; } int mid = (left+right)/2; if(target == A[mid]) return mid; if(A[mid] < A[right]){ // rotated pivot on the left if(target < A[mid]) return RSearch(A, left, mid, target); else{ if(target > A[right]) return RSearch(A, left, mid, target); else return RSearch(A, mid+1, right, target); } } else { //rotated pivot on the right if(target > A[mid]) return RSearch(A, mid+1, right, target); else{ if(target > A[right]) return RSearch(A, left, mid, target); else return RSearch(A, mid+1, right, target); } } } int search(int A[], int n, int target) { if(n <= 0) return -1; return RSearch(A, 0, n-1, target); }
No comments:
Post a Comment