Sort Stack
Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array).The stack supports the following operations: push, pop, peek, and isEmpty
Link here to the repo to solve the problem
πHints: #15, #32, #43
π Tips
One way of sorting an array is to iterate through the array and insert each element into a new array in sorted order. Can you do this with a stack?
Imagine your secondary stack is sorted. Can you insert elements into it in sorted order? You might need some extra storage. What could you use for extra storage?
Keep the secondary stack in sorted order, with the biggest elements on the top. Use the primary stack for additional storage.
π Solution 1
This approach utilises multiple stacks to keep track of every insert we do. We want to have a stack of numbers that are smaller than the one we are inserting and one with bigger than.
Once we have this we can repopulate the main stack in this order: bigger > inserted number > smaller than. This way the smaller number will always be at the top of the stack, sorting occurs at insertion.
public class SortStack {
private static Stack<Integer> stack = new Stack<>();
public void push(int i) {
if (stack.isEmpty()) stack.push(i);
else {
Stack<Integer> biggerThan = new Stack<>();
Stack<Integer> smallerThan = new Stack<>();
while (!stack.isEmpty()) {
Integer n = stack.pop();
if (n >= i) biggerThan.push(n);
else smallerThan.push(n);
}
while (!biggerThan.isEmpty()) {
stack.push(biggerThan.pop());
}
stack.push(i);
while (!smallerThan.isEmpty()) {
stack.push(smallerThan.pop());
}
}
}
public int pop() {
return stack.pop();
}
public int peek() {
return stack.peek();
}
public boolean isEmpty() {
return this.stack.isEmpty();
}
}