File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .Scanner ;
2+
3+ public class nextpermutation {
4+ public static int [] input () {
5+ System .out .println ("Enter the size array:" );
6+ Scanner sc = new Scanner (System .in );
7+ int n ;
8+ n = sc .nextInt ();
9+ int a [] = new int [n ];
10+ System .out .println ("Enter the array: " );
11+ for (int i = 0 ; i < n ; i ++) {
12+ a [i ] = sc .nextInt ();
13+ }
14+ return a ;
15+
16+ }
17+
18+ public static void print (int a []) {
19+ System .out .println ("The array: " );
20+ int n = a .length ;
21+ for (int i = 0 ; i < n ; i ++) {
22+ System .out .print (a [i ] + " " );
23+ }
24+ System .out .println ();
25+ }
26+ public static int [] nextPermutation (int [] nums ) {
27+ int i = nums .length - 2 ;
28+ while (i >= 0 && nums [i + 1 ] <= nums [i ]) {
29+ i --;
30+ }
31+ if (i >= 0 ) {
32+ int j = nums .length - 1 ;
33+ while (nums [j ] <= nums [i ]) {
34+ j --;
35+ }
36+ swap (nums , i , j );
37+ }
38+ reverse (nums , i + 1 );
39+ return nums ;
40+ }
41+
42+ private static void reverse (int [] nums , int start ) {
43+ int i = start , j = nums .length - 1 ;
44+ while (i < j ) {
45+ swap (nums , i , j );
46+ i ++;
47+ j --;
48+ }
49+ }
50+
51+ private static void swap (int [] nums , int i , int j ) {
52+ int temp = nums [i ];
53+ nums [i ] = nums [j ];
54+ nums [j ] = temp ;
55+ }
56+
57+ public static void main (String [] args ) {
58+ Scanner sc = new Scanner (System .in );
59+
60+
61+ int a [] = input ();
62+ int b []= nextPermutation (a );
63+ print (b );
64+
65+ }
66+ }
You can’t perform that action at this time.
0 commit comments