-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortStack.java
executable file
·39 lines (26 loc) · 971 Bytes
/
SortStack.java
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
import java.util.Stack;
public class SortStack {
public static void main(String args[]) {
Stack<Integer> originalStack = new Stack<>();
originalStack.add(14);
originalStack.add(9);
originalStack.add(67);
originalStack.add(91);
originalStack.add(101);
originalStack.add(25);
System.out.println("Original Stack: " + originalStack);
Stack<Integer> sortedStack= sorting(originalStack);
System.out.println("Sorted Stack is: " + sortedStack);
}
public static Stack<Integer> sorting(Stack<Integer> original) {
Stack<Integer> temporaryStack = new Stack<>();
while(!original.isEmpty()) {
int x = original.pop();
while(!temporaryStack.isEmpty() && temporaryStack.peek() > x) {
original.push(temporaryStack.pop());
}
temporaryStack.push(x);
}
return temporaryStack;
}
}