import java.io.*; import java.util.*; public class Lab_1 { /* * Johnson-Trotter algorithm to generate all permutations of the set {1, 2, ..., n} * * Author: Robin Dawes * * Date: 20080908 * */ static int n; static int[] nums; static int[] facing; static int maxMobileValue; static int maxMobileIndex; static boolean mobileElementExists = true; static BufferedReader in; public static void main(String[] argv) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)) ; System.out.print("How many numbers? "); n = Integer.valueOf(in.readLine()).intValue(); nums = new int[n]; facing = new int[n]; for (int i = 0; i < n; i++) { nums[i] = i+1; facing[i] = -1; } //for maxMobileValue = n; maxMobileIndex = n-1; show(); while (mobileElementExists) { //do the swap swap(); //show the new permutation show(); //find the next swap, if any mobileElementExists = false; maxMobileValue = 0; maxMobileIndex = -1; for (int i = 0; i < n; i++) if (isMobile(i)) { mobileElementExists = true; if (nums[i] > maxMobileValue) { maxMobileValue = nums[i]; maxMobileIndex = i; } } //if } //while } // main static boolean isMobile(int i){ return ((i > 0) && (facing[i] == -1) && (nums[i] > nums[i-1])) || ((i < n-1) && (facing[i] == 1) && (nums[i] > nums[i+1])); } //isMobile(int) static void swap() { int neighbour = maxMobileIndex + facing[maxMobileIndex]; nums[maxMobileIndex] = nums[neighbour]; nums[neighbour] = maxMobileValue; int temp = facing[maxMobileIndex]; facing[maxMobileIndex] = facing[neighbour]; facing[neighbour] = temp; for (int i = 0; i < n; i++) if (nums[i] > maxMobileValue) facing[i] *= -1; } //swap() static void show() { for (int i = 0; i < n; i++) System.out.print(nums[i] + "\t"); System.out.println(); } // show() } // class