Minimize count of swaps of adjacent elements required to make an array increasing | 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 ; Given array ; Store the size of the array
function minimumOperations ( A , n ) { var cnt = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( A [ i ] != ( i + 1 ) ) { if ( ( ( i - 1 ) >= 0 ) && A [ i - 1 ] == ( i + 1 ) ) { cnt ++ ; var 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 { document . write ( - 1 ) ; return ; } } } document . write ( cnt ) ; } var A = [ 7 , 3 , 2 , 1 , 4 ] ; var n = A . length ; minimumOperations ( A , n ) ;