Minimum number of swaps required to sort an array of first N number | Function to find minimum swaps ; Initialise count variable ; If current element is not at the right position ; Swap current element with correct position of that element ; Increment for next index when current element is at correct position ; Driver code ; Function to find minimum swaps
function minimumSwaps ( arr ) { let count = 0 ; let i = 0 ; while ( i < arr . length ) { if ( arr [ i ] != i + 1 ) { while ( arr [ i ] != i + 1 ) { let temp = 0 ; temp = arr [ arr [ i ] - 1 ] ; arr [ arr [ i ] - 1 ] = arr [ i ] ; arr [ i ] = temp ; count ++ ; } } i ++ ; } return count ; } let arr = [ 2 , 3 , 4 , 1 , 5 ] ; document . write ( minimumSwaps ( arr ) ) ;