-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnextpermutation.java
More file actions
52 lines (51 loc) · 1.23 KB
/
nextpermutation.java
File metadata and controls
52 lines (51 loc) · 1.23 KB
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
49
50
51
52
public class nextpermutation {
public static void main(String[] args) {
int[] A = {2, 1, 5, 4, 3, 0, 0};
nextPermutation(A);
System.out.print("The next permutation is: [");
for (int it : A) {
System.out.print(it + " ");
}
System.out.println("]");
}
public static void nextPermutation(int[] nums) {
int n = nums.length;
int ind=-1;
for(int i=n-2;i>=0;i--)
{
if(nums[i]<nums[i+1])
{
ind=i;
break;
}
}
if(ind==-1)
{
rev(nums,0,n-1);
return;
}
for(int i=n-1;i>ind;i--)
{
if(nums[i]>nums[ind])
{
swap(nums,i,ind);
break;
}
}
rev(nums,ind+1,n-1);
}
private static void rev(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}