Application of Binary Search - Circularly Rotated Array
#include<bits/stdc++.h>
#define min(x,y) x<y?x:y
using namespace std;
int min_index(int a[],int n){
int low=0,high=n-1;
while(low<=high){
if(a[low]<=a[high])
return low;
int mid = (low+high)/2;
int next=(mid+1)%n,prev=(mid+n-1)%n;
if(a[next]>=a[mid] && a[prev]>=a[mid])
return mid;
else if(a[mid]<=a[high])
high=mid-1;
else if(a[low]<=a[mid])
low=mid+1;
}
return -1;
}
int main()
{
int n,i=0;
cin>>n;
int a[n];
while(i<n)
cin>>a[i++];
int index = min_index(a,n);
int final_index =min(index,(n-index)%n);
cout<<final_index<<endl;
return 0;
}
/*
(1)
Input-
5
5 1 2 3 4
Output-
1
(2)
Input-
5
2 3 4 5 1
Output-
2
*/