I am trying to find the minimum element in a sorted array which has been rotated.
Example:
1 2 3 4 5 => sorted
3 4 5 1 2 => Rotated => Find the min in this in O(log n)
I have tried to write the code :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int bs(vector<int> a)
{
int l =0, r = a.size()-1;
while(l<=r)
{
int mid = l + (r-l)/2; // Mid guaranteed to be in range
if(a[mid-1]>a[mid]) return a[mid];
if(a[mid]>a[l])
{
l=mid+1 ; continue;
}
else
{
r = mid-1 ; //Mid has been checked
}
}
}
int main()
{
vector<int> a = {1,2,3,5,6,7,8,9,10};
rotate(a.begin(),a.begin()+4,a.end()); // Make 6 the head
for(auto x:a) cout<<x<<endl;
cout <<"Min is " <<bs(a) <<endl;
return 0;
}
I get the output:
6
7
8
9
10
1
2
3
5
Min is 3
, which is clearly wrong. I guess I am manipulating the binary search conditions to adapt to my problem, but I can't figure out what is wrong.
My method is similar to this, and I think I am doing logically correct, which is of course wrong thinking.