Search in Rotated Sorted Array

class Solution {
public:
    int search(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int left=0,right=n-1;
        while(left<=right){
            int mid=left+(right-left)/2;
            //left part is ordered
            if(A[left]<=A[mid]){
                int res=bsearch(A,left,mid,target);
                if(res!=-1) return res;
                else
                    left=mid+1;
            }else{
                int res=bsearch(A,mid+1,right,target);
                if(res!=-1) return res;
                else
                    right=mid;
            }
        }
        return -1;
    }
    
    int bsearch(int A[],int left,int right,int target){
        while(left<=right){
            int mid=left+(right-left)/2;
            if(A[mid]==target)
                return mid;
            else if(A[mid]>target)
                right=mid-1;
            else
                left=mid+1;
        }
        return -1;
    }
};


你可能感兴趣的:(Search in Rotated Sorted Array)