import java.util.Arrays;
public class NextGreaterPermutation {
public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
nextPermutation(nums);
System.out.println(Arrays.toString(nums));
nums = new int[] { 2, 3, 1 };
nextPermutation(nums);
System.out.println(Arrays.toString(nums));
}
public static void nextPermutation(int[] nums) {
int i = -1;
for (int j = nums.length - 2; j >= 0; j--) {
if (nums[j] < nums[j + 1]) {
i = j;
break;
}
}
if (i == -1) {
reverse(nums, 0);
return;
}
for (int j = nums.length - 1; j > i; j--) {
if (nums[j] > nums[i]) {
swap(nums, i, j);
break;
}
}
reverse(nums, i + 1);
}
private static void reverse(int[] nums, int start) {
int i = start, j = nums.length - 1;
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}