Skip to content

Instantly share code, notes, and snippets.

@z0marlin
Last active October 14, 2018 06:57
Show Gist options
  • Save z0marlin/9ca4ba5455efcc505e19633f1293cae0 to your computer and use it in GitHub Desktop.
Save z0marlin/9ca4ba5455efcc505e19633f1293cae0 to your computer and use it in GitHub Desktop.
Codebuddy week2 solution.
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