码迷,mamicode.com
首页 > 其他好文 > 详细

Search in Rotated Sorted Array

时间:2014-11-06 16:46:53      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   for   sp   

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.

 

Hide Tags
 Array Binary Search
 
class Solution {
public:
    int findPos(int a[],int left,int right){
        if(left>right)
            return -1;
        int mid=left+(right-left)/2;
        if(a[left]<=a[mid]){
            int pos=findPos(a,mid+1,right);
            if(pos==-1)
                return left;
            else
                return a[left]<=a[pos] ? left : pos;
        }else{
            int pos=findPos(a,left,mid-1);
            if(pos==-1)
                return mid;
            else
                return a[pos]<a[mid] ? pos : mid;
        }
    }
    
    int bsearch(int a[],int left,int right,int key){
        if(left>right)
            return -1;
        int mid=left+(right-left)/2;
        if(a[mid]==key)
            return mid;
        else if(a[mid]<key)
            return bsearch(a,mid+1,right,key);
        else 
            return bsearch(a,left,mid-1,key);
    }
    
    int search(int A[], int n, int target) {
        int pos=findPos(A,0,n-1);
        int index=bsearch(A,0,pos-1,target);
        if(index!=-1)
            return index;
        else
            return bsearch(A,pos,n-1,target);
    }
};

 

Search in Rotated Sorted Array

标签:style   blog   http   io   color   ar   os   for   sp   

原文地址:http://www.cnblogs.com/li303491/p/4078928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!