-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathStackSorting.java
More file actions
70 lines (59 loc) · 1.85 KB
/
StackSorting.java
File metadata and controls
70 lines (59 loc) · 1.85 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
//This code sorts the Stack in such a way that greatest element is at the top of the stack
/** Problem : Sort the Stack elements such that the greatest element is at the top of the stack
* Author : https://github.com/skmodi649
*/
import java.util.Scanner;
import java.util.Stack;
class StackSorting{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Stack size : ");
Stack<Integer> s=new Stack<>();
int n=sc.nextInt();
System.out.println("Enter the elements in the Stack : ");
while(n-->0)
s.push(sc.nextInt());
StackSorting g = new StackSorting();
System.out.println("Sorted Stack : ");
Stack<Integer> a = g.sort(s); //Sorted elements inserted in new Stack
while (!a.empty()) {
System.out.print(a.peek() + " ");
a.pop();
}
}
public void sortedInsert(Stack<Integer> S , int element) // This method inserts the sorted element
{
if((S.empty()) || (S.peek() < element))
S.push(element);
else
{
int temp = S.pop();
sortedInsert(S , element);
S.push(temp);
}
}
public Stack<Integer> sort(Stack<Integer> s) //Sorts the stack and then returns it
{
if(!s.empty())
{
int temp = s.pop();
sort(s);
sortedInsert(s , temp);
}
return s;
}
}
/** Expected Time Complexity: O(N*N)
* Expected Auxiliary Space Complexity : O(N)
* Constraints : 1<=N<=100
*/
/** Test Case 1 :
* Enter the Stack size : 5
* Enter the elements in the Stack : 0 1 2 3 9
* Sorted Stack : 9 3 2 1 0
*
* Test Case 2 :
* Enter the Stack size : 6
* Enter the elements in the Stack : 3 1 2 9 8 7
* Sorted Stack : 9 8 7 3 2 1
*/