Minimum number of swaps required to sort an array | Return the minimum number of swaps required to sort the array ; Dictionary which stores the indexes of the input array ; This is checking whether the current element is at the right place or not ; If not , swap this element with the index of the element which should come here ; Update the indexes in the hashmap accordingly ; Driver code ; Output will be 5
def minSwap ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE temp = arr . copy ( ) NEW_LINE h = { } NEW_LINE temp . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT h [ arr [ i ] ] = i NEW_LINE DEDENT init = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != temp [ i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE init = arr [ i ] NEW_LINE arr [ i ] , arr [ h [ temp [ i ] ] ] = arr [ h [ temp [ i ] ] ] , arr [ i ] NEW_LINE h [ init ] = h [ temp [ i ] ] NEW_LINE h [ temp [ i ] ] = i NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT a = [ 101 , 758 , 315 , 730 , 472 , 619 , 460 , 479 ] NEW_LINE n = len ( a ) NEW_LINE print ( minSwap ( a , n ) ) NEW_LINE