Count rotations required to sort given array in non | Java 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
import java . util . * ; class GFG { static void minMovesToSort ( int arr [ ] , int N ) { int count = 0 ; int index = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] < arr [ i + 1 ] ) { count ++ ; index = i ; } } if ( count == 0 ) { System . out . print ( "0" ) ; } else if ( count == N - 1 ) { System . out . print ( N - 1 ) ; } else if ( count == 1 && arr [ 0 ] <= arr [ N - 1 ] ) { System . out . print ( index + 1 ) ; } else { System . out . print ( " - 1" ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 1 , 5 , 4 , 2 } ; int N = arr . length ; minMovesToSort ( arr , N ) ; } }