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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ++ ; swap ( A [ i ] , A [ i - 1 ] ) ; } 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 { cout << -1 ; return ; } } } cout << cnt ; } int main ( ) { int A [ ] = { 7 , 3 , 2 , 1 , 4 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; minimumOperations ( A , n ) ; return 0 ; }