Examples:
Input:
arr[]= {4,5, 1, 2, 3}
Output:
rotation count: 2
Input:
arr[]= {50, 10, 20, 30, 40}
Output:
rotation count : 1
#include <bits/stdc++.h>
using namespace std;
// Function to find the k rotation value
int rotationCount(int arr[], int n)
{
int l = 0, r = n - 1;
while (l <= r)
{
// find middle, previous and next element
int mid = l + (r - l) / 2;
int prev = (mid - 1 + n) % n;
int next = (mid + 1) % n;
// compare mid element with next and previous
if (arr[mid] <= arr[prev] && arr[mid] <= arr[next])
return mid;
else if (arr[mid] <= arr[r])
r = mid - 1;
else if (arr[mid] >= arr[l])
l = mid + 1;
}
return 0;
}
// Main function
int main()
{
int arr[100], N, element;
cout << "Enter size of array: ";
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
cout << "Rotation Count: " << rotationCount(arr, N);
return 0;
}
Output:
Enter size of array: 5
4 5 1 2 3
Rotation Count: 2
0 Comments