Question -
Given an sorted array, to check that array is rotated or not.
Example -
Input : arr[] = {1,2,3,4,5} , n=5
Output : Array is not rotated.
Input : arr[] = {3,4,5,1,2}
Output : Array is rotated.
Approch -
if any sorted array is not rotated then its first value is always less than last value and if first value is not less than last value then array is rotated.
Solution-
// to check that given sorted array is rotated or not
#include<iostream>
using namespace std;
int checkrotation(int arr[],int n)
{
if(arr[0]>arr[n-1])
return 1;
else
return 0;
}
int main()
{
int n;
cout<<"Enter the no of element : ";cin>>n;
cout<<"Enter "<<n<<" elements : "<<endl;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int check;
check=checkrotation(arr,n);
if(check)
cout<<"Array is rotated."<<endl;
else
cout<<"Array is not rotated."<<endl;
return 0;
}
Time complixity - O(1)
Comments
Post a Comment