Question -
To calculate the no of clockwise rotation in sorted and rotated array
Example -
Input : arr[] = {4,5,1,2,3} , n=5
Output : 2
Input : arr[] = {10,12,14,2,5} n=5
Output : 3
Approach -
first we calculate pivot element of rotated and sorted array, and index of pivot element +1 is the no of rotation.
Implementation -
//using binary search
#include<iostream>
using namespace std;
int countrotation(int arr[],int n)
{
int low=0;
int high=n-1;
int mid;
while(low<=high){
mid=(low+high)/2;
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 count=countrotation(arr,n);
cout<<"No of rotation is : "<<count+1<<endl;
return 0;
}
Time complixity - O(logn)
Comments
Post a Comment