Lexicographically smallest permutation with no digits at Original Index | Java program to find the smallest permutation ; Function to print the smallest permutation ; when n is even ; when n is odd ; handling last 3 digit ; add EOL and print result ; Driver Code
class GFG { static void smallestPermute ( int n ) { char res [ ] = new char [ n + 1 ] ; if ( n % 2 == 0 ) { for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = ( char ) ( 48 + i + 2 ) ; else res [ i ] = ( char ) ( 48 + i ) ; } } else { for ( int i = 0 ; i < n - 2 ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = ( char ) ( 48 + i + 2 ) ; else res [ i ] = ( char ) ( 48 + i ) ; } res [ n - 1 ] = ( char ) ( 48 + n - 2 ) ; res [ n - 2 ] = ( char ) ( 48 + n ) ; res [ n - 3 ] = ( char ) ( 48 + n - 1 ) ; } res [ n ] = ' \0' ; for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( res [ i ] ) ; } } public static void main ( String [ ] args ) { int n = 7 ; smallestPermute ( n ) ; } }