Lexicographically smallest array after at | Modifies arr [ 0. . n - 1 ] to lexicographically smallest with k swaps . ; Set the position where we want to put the smallest integer ; If we exceed the Max swaps then terminate the loop ; Find the minimum value from i + 1 to max k or n ; Swap the elements from Minimum position we found till now to the i index ; Set the final value after swapping pos - i elements ; Driver method ; Function calling ; Print the final Array
function minimizeWithKSwaps ( arr , n , k ) { for ( let i = 0 ; i < n - 1 && k > 0 ; ++ i ) { let pos = i ; for ( let j = i + 1 ; j < n ; ++ j ) { if ( j - i > k ) break ; if ( arr [ j ] < arr [ pos ] ) pos = j ; } let temp ; for ( let j = pos ; j > i ; -- j ) { temp = arr [ j ] ; arr [ j ] = arr [ j - 1 ] ; arr [ j - 1 ] = temp ; } k -= pos - i ; } } let arr = [ 7 , 6 , 9 , 2 , 1 ] ; let n = arr . length ; let k = 3 ; minimizeWithKSwaps ( arr , n , k ) ; document . write ( " " ) ; for ( let i = 0 ; i < n ; ++ i ) document . write ( arr [ i ] + " " ) ;