-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortStack.java
More file actions
60 lines (50 loc) · 1.35 KB
/
SortStack.java
File metadata and controls
60 lines (50 loc) · 1.35 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
package learn.ds.stack;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
/**
* @author Varma Penmetsa
*
* https://www.geeksforgeeks.org/sort-a-stack-using-recursion/
*/
public class SortStack {
//Using Recursion
public static void sort(Deque<Integer> st){
if(st.isEmpty())
return;
int val = st.pop();
sort(st);
sortedInsert(st,val);
}
public static void sortedInsert(Deque<Integer> st ,int val){
if(st.isEmpty() || val > st.peek()){
st.push(val);
return;
}else {
int v = st.pop();
sortedInsert(st,val);
st.push(v);
}
}
//Iteration O(n^2)
public static Deque<Integer> sort2(Deque<Integer> input){
Deque<Integer> tmpStack = new ArrayDeque<>();
while (!input.isEmpty()) {
int tmp = input.pop();
while (!tmpStack.isEmpty() && tmpStack.peek() > tmp) {
input.push(tmpStack.pop());
}
tmpStack.push(tmp);
}
return tmpStack;
}
public static void main(String[] args) {
Deque<Integer> st = new ArrayDeque<>();
st.push(5);
st.push(7);
st.push(1);
st.push(-9);
st.push(2);
System.out.println(Arrays.toString(sort2(st).toArray()));
}
}