File tree Expand file tree Collapse file tree 2 files changed +96
-0
lines changed Expand file tree Collapse file tree 2 files changed +96
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* package codechef; // don't place package name! */
2
+
3
+ import java .util .*;
4
+ import java .lang .*;
5
+ import java .io .*;
6
+
7
+ /* Name of the class has to be "Main" only if the class is public. */
8
+ class Codechef
9
+ {
10
+ public static void main (String [] args ) throws java .lang .Exception
11
+ {
12
+ int l [] = {1 , 2 , 4 , 6 };
13
+ int r [] = {3 , 5 , 7 , 8 };
14
+ int nL = l .length ;
15
+ int nR = r .length ;
16
+ int a [] = new int [nL + nR ];
17
+ int i = 0 , j = 0 , k = 0 ;
18
+ while (i < nL && j < nR ) {
19
+ if (l [i ] <= r [j ]) {
20
+ a [k ] = l [i ];
21
+ i ++;
22
+ }
23
+ else {
24
+ a [k ] = r [j ];
25
+ j ++;
26
+ }
27
+ k ++;
28
+ }
29
+ while (i < nL ) {
30
+ a [k ++] = l [i ++];
31
+ }
32
+ while (j < nR ) {
33
+ a [k ++] = r [j ++];
34
+ }
35
+ for (int m = 0 ; m < k ; m ++) {
36
+ System .out .print (a [m ] + " " );
37
+ }
38
+ }
39
+ }
Original file line number Diff line number Diff line change
1
+ import java .util .*;
2
+ import java .lang .*;
3
+ import java .io .*;
4
+ class GFG
5
+ {
6
+ public static void main (String [] args )
7
+ {
8
+ Scanner sc = new Scanner (System .in );
9
+ int t = sc .nextInt ();
10
+ while (t -- != 0 ) {
11
+ int n = sc .nextInt ();
12
+ int a [] = new int [n ];
13
+ for (int i = 0 ; i < n ; i ++) {
14
+ a [i ] = sc .nextInt ();
15
+ }
16
+ int i = 0 ;
17
+ int f = 0 ;
18
+ int r = a .length - 1 ;
19
+ // Finding the Number which breakes the ascending order pattern from right
20
+ for (int j = a .length - 1 ; j > 0 ; j --) {
21
+ if (a [j - 1 ] < a [j ]) {
22
+ f = 1 ;
23
+ i = j - 1 ;
24
+ break ;
25
+ }
26
+ }
27
+ if (f == 1 ) {
28
+ // Finding the Smallest number which is greater than a[i]
29
+ int min = 1111 ;
30
+ for (int q = i + 1 ; q < n ; q ++) {
31
+ if (a [q ] > a [i ] && a [q ] < min ) {
32
+ min = a [q ];
33
+ r = q ;
34
+ }
35
+ }
36
+ // Swapping numbers
37
+ int temp = a [i ];
38
+ a [i ] = a [r ];
39
+ a [r ] = temp ;
40
+ // Sorting numbers
41
+ Arrays .sort (a , i + 1 , n );
42
+ // Printing the numbers
43
+ for (int j = 0 ; j < a .length ; j ++) {
44
+ System .out .print (a [j ] + " " );
45
+ }
46
+ System .out .println ();
47
+ }
48
+ else {
49
+ // Printing in reverse order if the numbers are found in descending order
50
+ for (i = a .length - 1 ; i >= 0 ; i --) {
51
+ System .out .print (a [i ] + " " );
52
+ }
53
+ }
54
+ f = 0 ;
55
+ }
56
+ }
57
+ }
You can’t perform that action at this time.
0 commit comments