-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathR14sortStack.java
More file actions
50 lines (45 loc) · 1.1 KB
/
R14sortStack.java
File metadata and controls
50 lines (45 loc) · 1.1 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
import java.util.*;
public class R14sortStack {
static void sortedInsert(Stack<Integer> s, int x)
{
// Base case
if (s.isEmpty() || x > s.peek()) {
s.push(x);
return;
}
// If top is greater remove the top item
int temp = s.pop();
sortedInsert(s, x);
s.push(temp);
}
static void sortStack(Stack<Integer> s)
{
// If stack is not empty
if (!s.isEmpty()) {
// Remove the top item
int x = s.pop();
// Sort remaining stack
sortStack(s);
// Push the top item back in sorted stack
sortedInsert(s, x);
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
Stack<Integer> s= new Stack<>();
while(n!=0)
{
int tmp=sc.nextInt();
s.push(tmp);
n--;
}
sortStack(s);
while(!s.isEmpty())
{
System.out.print(s.peek()+ " ");
s.pop();
}
}
}