-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay78.java
More file actions
35 lines (32 loc) · 953 Bytes
/
Day78.java
File metadata and controls
35 lines (32 loc) · 953 Bytes
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
import java.util.Stack;
public class Day78 {
public static void sortStack(Stack<Integer> stack) {
if (!stack.isEmpty()) {
int temp = stack.pop();
sortStack(stack);
insertAtRightPlace(stack, temp);
}
}
private static void insertAtRightPlace(Stack<Integer> stack, int element) {
if (stack.isEmpty() || stack.peek() <= element) {
stack.push(element);
return;
}
int temp = stack.pop();
insertAtRightPlace(stack, element);
stack.push(temp);
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(5);
stack.push(-2);
stack.push(9);
stack.push(-7);
stack.push(3);
sortStack(stack);
System.out.print("Sorted Stack: ");
while (!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
}
}