Find the Rotation Count in Rotated Sorted array in C++


Consider we have an array, which is rotated sorted array. We have to find number of rotations are required to sort the array. (We will consider rotation right to left.)

Suppose the array is like: {15, 17, 1, 2, 6, 11}, then we have to rotate the array two times to sort. The final order will be {1, 2, 6, 11, 15, 17}. Here output is 2.

The logic is simple. If we notice, we can see that the number of rotation is same as the value of index of minimum element. So if we get the minimum element, then its index will be the result.

Example

 Live Demo

#include <iostream>
using namespace std;
int getMinIndex(int arr[], int n){
   int index = 0;
   for(int i = 1; i<n; i++){
      if(arr[i] < arr[index]){
         index = i;
      }
   }
   return index;
}
int countNumberOfRotations(int arr[], int n){
   return getMinIndex(arr, n);
}
int main() {
   int arr[] = {15, 17, 1, 2, 6, 11};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Number of required rotations: " << countNumberOfRotations(arr, n);
}

Output

Number of required rotations: 2

Updated on: 21-Oct-2019

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements