Repository navigation
Expand file tree
/
Copy pathNextPermutation.java
More file actions
78 lines (52 loc) · 1.46 KB
/
Copy pathNextPermutation.java
File metadata and controls
78 lines (52 loc) · 1.46 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package Algorithms;
import com.sun.source.tree.AssertTree;
import java.util.Arrays;
public class NextPermutation {
public static void swap(int [] arr, int i , int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public void reverse(int [] arr, int pivot){
//reverse the values after the index pivot
int n = arr.length;
int i = pivot, j = n-1;
while(i<j && i<n && j>= pivot){
swap(arr, i, j);
}
}
public static void nextPermutation(int []arr){
//algorithm
// int [] ans = Arrays.copyOf(arr, arr.length);
int n = arr.length;
int pivot = -1;
for(int i = n-2; i>=0; i-- ){
if(arr[i]< arr[i+1]){
pivot = i;
int j = n - 1;
while(j > i){
if(arr[j] > arr[i]){
swap(arr, i , j);
break;
}
}
break;
}
}
//3 2 1 5 4
//1 2 3 4 5
}
public String nextPermutation(String s){
return s;
}
public static void main(String[] args) {
int arr [] = {1, 2, 3, 4, 5};
nextPermutation(arr);
if(!Arrays.equals(arr, new int[]{1,2,3,5,4})){
throw new AssertionError("Test failed");
}
else {
System.out.println("Test passed");
}
}
}