Skip to content

Commit 5ba1eca

Browse files
committed
Added sort a stack from CTCI - Easy
1 parent 93c46f7 commit 5ba1eca

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import java.util.*;
2+
3+
public class MyClass {
4+
public static void main(String args[]) {
5+
// Create an example stack and add items to it
6+
Stack<Integer> s = new Stack<>();
7+
int[] numbers = new int[]{5, 7, 3, 6, 7, 3, 27, 4};
8+
for (int num : numbers) {
9+
s.push(num);
10+
}
11+
// Call the sorting function we created below
12+
sort(s);
13+
while (!s.isEmpty()) {
14+
// Print to see that the sorting actually worked
15+
System.out.print(s.pop() + ",");
16+
}
17+
18+
}
19+
20+
/*
21+
The idea is to create an additional stack
22+
which will be sorted and we maintain it's state by
23+
popping larger elements out and pushing smaller elements in
24+
25+
*/
26+
public static void sort(Stack<Integer> main) {
27+
Stack<Integer> temp = new Stack<>();
28+
// While there are elements in main
29+
while (!main.isEmpty()) {
30+
// Pick a pivot value
31+
int pivot = main.pop();
32+
// While we have bigger values in temp, pop em out
33+
while (!temp.isEmpty() && temp.peek() > pivot) {
34+
main.push(temp.pop());
35+
}
36+
// otherwise, push pivot in
37+
temp.push(pivot);
38+
39+
}
40+
// Add the elements back into main so that they appear in
41+
// Ascending order
42+
while (!temp.isEmpty()) {
43+
main.push(temp.pop());
44+
}
45+
}
46+
47+
}

0 commit comments

Comments
 (0)