Skip to content

Instantly share code, notes, and snippets.

@deadcoder0904
Created September 9, 2016 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deadcoder0904/9548dc971ae1925a378aefb31fe728d3 to your computer and use it in GitHub Desktop.
Save deadcoder0904/9548dc971ae1925a378aefb31fe728d3 to your computer and use it in GitHub Desktop.
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
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment