Lexicographically n | Java program to print nth permutation with using next_permute ( ) ; Function to print nth permutation using next_permute ( ) ; Sort the string in lexicographically ascending order ; Keep iterating until we reach nth position ; check for nth iteration ; print string after nth iteration ; Utility function ; Driver code
import java . util . * ; class GFG { static void nPermute ( char [ ] str , int n ) { Arrays . sort ( str ) ; int i = 1 ; do { if ( i == n ) break ; i ++ ; } while ( next_permutation ( str ) ) ; System . out . println ( String . valueOf ( str ) ) ; } static boolean next_permutation ( char [ ] p ) { for ( int a = p . length - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( int b = p . length - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { char t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } public static void main ( String [ ] args ) { String str = " GEEKSFORGEEKS " ; int n = 100 ; nPermute ( str . toCharArray ( ) , n ) ; } }