In this code I am taking an sorted array that is circularly shifted k position as an input and I need to find the largest element in the array in O(log n) so I used the logic as such that if the element at 0 index in sorted array is same as circularly array then return the value of position for the same I used binary search but I am getting -1 from the function
Here is the code:
#include<iostream>
#include<algorithm>
using namespace std;
int position(int ar[],int start,int end,int item ){
int mid;
if(end >= start)
{
mid = (start + end)/2;
if(ar[mid] == item)
{
return mid+1;
}
else if(ar[mid] < item)
{
return position(ar,mid+1,end,item);
}
else
{
return position(ar,start,mid-1,item);
}
}
}
int main(){
int l,e=0,pos=0,k=0,lar=0;
cout<<endl<<"Enter the length of the array = ";
cin>>l;
int arr[l],temp[l];
cout<<endl<<"Enter the array elements:-"<<endl;
for(int i=0;i<l;i++){
cout<<"Enter the element at "<<(i+1)<<" = ";
cin>>arr[i];
temp[i]=arr[i];
}
sort(temp,temp+l);
e=temp[0];
k=position(arr,0,l,e);
lar=arr[k-1];
cout<<endl<<"Value of k = "<<k<<endl;
cout<<endl<<"largest element in the array is "<<lar<<endl;
return 0;
}