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 ; Driver Code ; Given array ; Store the size of the array
def minimumOperations ( A , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ i ] != ( i + 1 ) ) : NEW_LINE INDENT if ( ( ( i - 1 ) >= 0 ) and A [ i - 1 ] == ( i + 1 ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE A [ i ] , A [ i - 1 ] = A [ i - 1 ] , A [ i ] NEW_LINE DEDENT elif ( ( ( i - 2 ) >= 0 ) and A [ i - 2 ] == ( i + 1 ) ) : NEW_LINE INDENT cnt += 2 NEW_LINE A [ i - 2 ] = A [ i - 1 ] NEW_LINE A [ i - 1 ] = A [ i ] NEW_LINE A [ i ] = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( cnt ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 7 , 3 , 2 , 1 , 4 ] NEW_LINE n = len ( A ) NEW_LINE minimumOperations ( A , n ) NEW_LINE DEDENT