Last active
October 14, 2018 06:57
-
-
Save z0marlin/9ca4ba5455efcc505e19633f1293cae0 to your computer and use it in GitHub Desktop.
Codebuddy week2 solution.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int pivot(const vector<int> &A){ | |
int l=0; | |
int r=A.size()-1; | |
int mid; | |
while(l<r){ | |
mid=(r-l)/2+l; | |
if(mid>l && A[mid-1]>A[mid]){ | |
return mid; | |
} | |
if(mid<r && A[mid+1]<A[mid]){ | |
return mid+1; | |
} | |
if(A[r]>A[mid]){ | |
r=mid-1; | |
} | |
else{ | |
l=mid+1; | |
} | |
} | |
return 0; | |
} | |
int bSearch(const vector<int> &A,int l,int r,int key){ | |
int mid; | |
while(l<=r){ | |
mid=(r-l)/2+l; | |
if(A[mid]==key){ | |
return mid; | |
} | |
if(A[mid]>key){ | |
r=mid-1; | |
} | |
else{ | |
l=mid+1; | |
} | |
} | |
return -1; | |
} | |
int Solution::search(const vector<int> &A, int B) { | |
int p=pivot(A); | |
int s=bSearch(A,0,p-1,B); | |
if(s!=-1) | |
return s; | |
s=bSearch(A,p,A.size()-1,B); | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment