import java.util.Scanner; public class PermutationFinder { public static void Permutation(int[] a) { boolean flag1 = true; while (flag1) { // Find k : Step 1 int k = a.length - 2; boolean flag = true; while (k >= 0 && flag) { if (a[k] < a[k+1]) { flag = false; } else { k--; } } if (flag) // k = -1 -> You have reached the end - No more permutations { flag1 = false; } else // Find the next permutation { // Step 2 : Find l int l = a.length - 1; while (a[k] > a[l]) { l--; } // Step 3 : Swap a[k] and a[l] int temp = a[k]; a[k] = a[l]; a[l] = temp; // Step 4 : Starting from the end of the array and until k +1 , swap the corresponding cells int s = k + 1; for (int r = a.length-1; r > s; r--) // when r == s, step 4 has completed { temp = a[r]; a[r] = a[s]; a[s] = temp; s++; } for (int i = 0; i < a.length; i++) { System.out.print(a[i]); } System.out.println("\n"); } } } public static void main(String[] args) { System.out.println ("Permutation - Lexicographical Order"); Scanner scan = new Scanner (System.in); System.out.println ("Input N"); int n = scan.nextInt(); int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = i+1; } for (int i = 0; i < a.length; i++) { System.out.print(a[i]); } System.out.println("\n"); Permutation(a); } }