Minimum number of swaps required to sort an array | swap function ; indexOf function ; Return the minimum number of swaps required to sort the array ; This is checking whether the current element is at the right place or not ; Swap the current element with the right index so that arr [ 0 ] to arr [ i ] is sorted ; Driver code ; Output will be 5
def swap ( arr , i , j ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE arr [ i ] = arr [ j ] NEW_LINE arr [ j ] = temp NEW_LINE DEDENT def indexOf ( arr , ele ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] == ele ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def minSwaps ( arr , N ) : NEW_LINE INDENT ans = 0 NEW_LINE temp = arr . copy ( ) NEW_LINE temp . sort ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] != temp [ i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE swap ( arr , i , indexOf ( arr , temp [ i ] ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 101 , 758 , 315 , 730 , 472 , 619 , 460 , 479 ] NEW_LINE n = len ( a ) NEW_LINE print ( minSwaps ( a , n ) ) NEW_LINE DEDENT