Count rotations required to sort given array in non | C ++ program for the above approach ; Function to count minimum anti - clockwise rotations required to sort the array in non - increasing order ; Stores count of arr [ i + 1 ] > arr [ i ] ; Store last index of arr [ i + 1 ] > arr [ i ] ; Traverse the given array ; If the adjacent elements are in increasing order ; Increment count ; Update index ; Print the result according to the following conditions ; Otherwise , it is not possible to sort the array ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minMovesToSort ( int arr [ ] , int N ) { int count = 0 ; int index ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] < arr [ i + 1 ] ) { count ++ ; index = i ; } } if ( count == 0 ) { cout << "0" ; } else if ( count == N - 1 ) { cout << N - 1 ; } else if ( count == 1 && arr [ 0 ] <= arr [ N - 1 ] ) { cout << index + 1 ; } else { cout << " - 1" ; } } int main ( ) { int arr [ ] = { 2 , 1 , 5 , 4 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minMovesToSort ( arr , N ) ; return 0 ; }