|
| 1 | +//Implement next permutation, which rearranges numbers into the lexicographically |
| 2 | +//next greater permutation of numbers. |
| 3 | + |
| 4 | +import java.util.Scanner; |
| 5 | + |
| 6 | +public class nextpermutation { |
| 7 | + |
| 8 | + //This function is used to take input and store in array |
| 9 | + public static int[] input() { |
| 10 | + System.out.println("Enter the size array:"); |
| 11 | + Scanner sc = new Scanner(System.in); |
| 12 | + int n; |
| 13 | + n = sc.nextInt(); |
| 14 | + int a[] = new int[n]; |
| 15 | + System.out.println("Enter the array: "); |
| 16 | + for (int i = 0; i < n; i++) { |
| 17 | + a[i] = sc.nextInt(); |
| 18 | + } |
| 19 | + return a; |
| 20 | + |
| 21 | + } |
| 22 | +//This function is used to print the desired output |
| 23 | + public static void print(int a[]) { |
| 24 | + System.out.println("The array: "); |
| 25 | + int n = a.length; |
| 26 | + for (int i = 0; i < n; i++) { |
| 27 | + System.out.print(a[i] + " "); |
| 28 | + } |
| 29 | + System.out.println(); |
| 30 | + } |
| 31 | + public static int[] nextPermutation(int[] nums) { |
| 32 | + int i = nums.length - 2; |
| 33 | + while (i >= 0 && nums[i + 1] <= nums[i]) { |
| 34 | + i--; |
| 35 | + } |
| 36 | + // sort from i + 1 or reverse it as you will get decreasing order from i + 1 |
| 37 | + if (i >= 0) { |
| 38 | + int j = nums.length - 1; |
| 39 | + while (nums[j] <= nums[i]) { |
| 40 | + j--; |
| 41 | + } |
| 42 | + swap(nums, i, j); |
| 43 | + } |
| 44 | + reverse(nums, i + 1); |
| 45 | + return nums; |
| 46 | + } |
| 47 | + |
| 48 | + private static void reverse(int[] nums, int start) { |
| 49 | + int i = start, j = nums.length - 1; |
| 50 | + while (i < j) { |
| 51 | + swap(nums, i, j); |
| 52 | + i++; |
| 53 | + j--; |
| 54 | + } |
| 55 | + } |
| 56 | + //Actual function to swapp |
| 57 | + private static void swap(int[] nums, int i, int j) { |
| 58 | + int temp = nums[i]; |
| 59 | + nums[i] = nums[j]; |
| 60 | + nums[j] = temp; |
| 61 | + } |
| 62 | + |
| 63 | + public static void main(String[] args) { |
| 64 | + Scanner sc = new Scanner(System.in); |
| 65 | + |
| 66 | + |
| 67 | + int a[] = input(); |
| 68 | + int b[]= nextPermutation(a); |
| 69 | + print(b); |
| 70 | + |
| 71 | + } |
| 72 | +} |
0 commit comments