-
Notifications
You must be signed in to change notification settings - Fork 5
/
NextPermutation.java
executable file
·48 lines (46 loc) · 1.29 KB
/
NextPermutation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package array;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class NextPermutation {
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String line=br.readLine();
String[] temp=line.trim().split("\\s+");
int[] arr=new int[n];
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(temp[i]);
nextPermutation(arr);
for(int o: arr) System.out.print(o+" ");
br.close();
}
private static void nextPermutation(int[] nums) {
int r1=-1, r2=-1;
for(int i=nums.length-1;i>0;i--){
if(nums[i]>nums[i-1]){
r1=i-1;
break;
}
}
if(r1==-1){
Arrays.sort(nums);
return;
}
for(int i=nums.length-1;i>0;i--){
if(nums[i]>nums[r1]){
r2=i;
break;
}
}
int t=nums[r1];
nums[r1]=nums[r2];
nums[r2]=t;
for(int i=r1+1, j= nums.length-1;i<j;i++,j--){
t=nums[j];
nums[j]=nums[i];
nums[i]=t;
}
}
}