1+ //This code sorts the Stack in such a way that greatest element is at the top of the stack
2+
3+ /** Problem : Sort the Stack elements such that the greatest element is at the top of the stack
4+ * Author : https://github.com/skmodi649
5+ */
6+
7+
8+
9+ import java .util .Scanner ;
10+ import java .util .Stack ;
11+
12+ class StackSorting {
13+ public static void main (String [] args ){
14+ Scanner sc =new Scanner (System .in );
15+ System .out .println ("Enter the Stack size : " );
16+ Stack <Integer > s =new Stack <>();
17+ int n =sc .nextInt ();
18+ System .out .println ("Enter the elements in the Stack : " );
19+ while (n -->0 )
20+ s .push (sc .nextInt ());
21+ StackSorting g = new StackSorting ();
22+ System .out .println ("Sorted Stack : " );
23+ Stack <Integer > a = g .sort (s ); //Sorted elements inserted in new Stack
24+ while (!a .empty ()) {
25+ System .out .print (a .peek () + " " );
26+ a .pop ();
27+ }
28+ }
29+
30+ public void sortedInsert (Stack <Integer > S , int element ) // This method inserts the sorted element
31+ {
32+ if ((S .empty ()) || (S .peek () < element ))
33+ S .push (element );
34+ else
35+ {
36+ int temp = S .pop ();
37+ sortedInsert (S , element );
38+ S .push (temp );
39+ }
40+ }
41+ public Stack <Integer > sort (Stack <Integer > s ) //Sorts the stack and then returns it
42+ {
43+ if (!s .empty ())
44+ {
45+ int temp = s .pop ();
46+ sort (s );
47+ sortedInsert (s , temp );
48+ }
49+ return s ;
50+ }
51+ }
52+
53+
54+
55+ /** Expected Time Complexity: O(N*N)
56+ * Expected Auxiliary Space Complexity : O(N)
57+ * Constraints : 1<=N<=100
58+ */
59+
60+
61+ /** Test Case 1 :
62+ * Enter the Stack size : 5
63+ * Enter the elements in the Stack : 0 1 2 3 9
64+ * Sorted Stack : 9 3 2 1 0
65+ *
66+ * Test Case 2 :
67+ * Enter the Stack size : 6
68+ * Enter the elements in the Stack : 3 1 2 9 8 7
69+ * Sorted Stack : 9 8 7 3 2 1
70+ */
0 commit comments