Minimize count of swaps of adjacent elements required to make an array increasing | C # program for the above approach ; Function to count minimum number of operations required to obtain an increasing array from given array A [ ] ; Store the required result ; Traverse the array A [ ] ; If the current element is not in its correct position ; Check if it is present at index i - 1 ; Check if it is present at index i - 2 ; Otherwise , print - 1 ( Since A [ i ] can not be swapped more than twice ) ; Print the result ; Driver code ; Given array ; Store the size of the array
using System ; class GFG { static void minimumOperations ( int [ ] A , int n ) { int cnt = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( A [ i ] != ( i + 1 ) ) { if ( ( ( i - 1 ) >= 0 ) && A [ i - 1 ] == ( i + 1 ) ) { cnt ++ ; int t = A [ i ] ; A [ i ] = A [ i - 1 ] ; A [ i - 1 ] = t ; } else if ( ( ( i - 2 ) >= 0 ) && A [ i - 2 ] == ( i + 1 ) ) { cnt += 2 ; A [ i - 2 ] = A [ i - 1 ] ; A [ i - 1 ] = A [ i ] ; A [ i ] = i + 1 ; } else { Console . WriteLine ( - 1 ) ; return ; } } } Console . WriteLine ( cnt ) ; } public static void Main ( ) { int [ ] A = { 7 , 3 , 2 , 1 , 4 } ; int n = A . Length ; minimumOperations ( A , n ) ; } }