//find the smallest and largest element in sorted and rotated array
#include<iostream>
using namespace std;
int findpivot(int arr[],int n)
{
int low=0;
int high=n-1;
int mid;
while(low<=high){
if(mid<high&&arr[mid]>arr[mid+1])
return mid;
if(mid>low&&arr[mid]<arr[mid-1])
return mid-1;
if(arr[low]>arr[mid])
high=mid-1;
else
low=mid+1;
}
}
int main()
{
int n;
cout<<"Enter the no of element : ";cin>>n;
int arr[n];
cout<<"Enter elements : "<<endl;
for (int i=0;i<n;i++)
cin>>arr[i];
int pivot=findpivot(arr,n);
cout<<"smallest number is : "<<arr[pivot+1]<<endl<<"largest number is : "<<arr[pivot]<<endl;
return 0;
}
Note - this logic is only applicable on sorted and rotated array, not applicable at sorted array.
Time complixity - O(logn)
Comments
Post a Comment