Complexity O(logN) by binary search
int Arr[5]={4,5,1,2,3},l=0,r=4,mid,X,ans=-1;
cin>>X;
Initialise the array Arr on which we are performing binary search.
X is the number we are trying to find , l=0 and r=sizeof(Arr)-1
ans is index of X, -1 if not present in array.
We have two condition when our given X will be in first half then we will update r to mid-1.
Case 1. Rotation point is in the first half and X also.
(Arr[l] > Arr[mid] && (X>=Arr[l] || X<=Arr[mid]))
It ensure that rotation point is in first half by Arr[l] > Arr[mid] and if X>=Arr[l] then X can only be in first half and X<=Arr[mid] then also X can only be in first half.
Case 2. Rotation point is in second half but X is in first half
(Arr[l]<=Arr[mid] && (X>=Arr[l] && X<=Arr[mid]))
If Arr[mid]==X then update answer and break loop.
while(l<=r){
cout<<l<<r<<" ";
mid=(l+r)/2;
if(Arr[mid]==X){
ans=mid;
break;
}
if((Arr[l] > Arr[mid] && (X>=Arr[l] || X<=Arr[mid]))
|| (Arr[l]<=Arr[mid] && (X>=Arr[l] && X<=Arr[mid])))
r=mid-1;
else
l=mid+1;
}
cout<<ans;