text: Lexicographically smallest array after at | C # program to find lexicographically minimum value after k swaps . ; 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
code: using System ; class GFG { static void minimizeWithKSwaps ( int [ ] arr , int n , int k ) { for ( int i = 0 ; i < n - 1 && k > 0 ; ++ i ) { int pos = i ; for ( int j = i + 1 ; j < n ; ++ j ) { if ( j - i > k ) break ; if ( arr [ j ] < arr [ pos ] ) pos = j ; } int temp ; for ( int j = pos ; j > i ; -- j ) { temp = arr [ j ] ; arr [ j ] = arr [ j - 1 ] ; arr [ j - 1 ] = temp ; } k -= pos - i ; } } public static void Main ( ) { int [ ] arr = { 7 , 6 , 9 , 2 , 1 } ; int n = arr . Length ; int k = 3 ; minimizeWithKSwaps ( arr , n , k ) ; for ( int i = 0 ; i < n ; ++ i ) Console . Write ( arr [ i ] + " ▁ " ) ; } }