Can someone help look at my code, please? Thank you so much for your help. The input stack is [5, 2, 1, 9, 0, 10], my codes gave output stack [0, 9, 1, 2, 5, 10], 9 is not i
Here's my version of the code which is pretty straightforward to follow.
import java.util.Stack;
public class StackSorting {
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(12);
stack.push(100);
stack.push(13);
stack.push(50);
stack.push(4);
System.out.println("Elements on stack before sorting: "+ stack.toString());
stack = sort(stack);
System.out.println("Elements on stack after sorting: "+ stack.toString());
}
private static Stack sort(Stack stack) {
if (stack.isEmpty()) {
return null;
}
Stack sortedStack = new Stack();
int element = 0;
while(!stack.isEmpty()) {
if (stack.peek() <= (element = stack.pop())) {
if (sortedStack.isEmpty()) {
sortedStack.push(element);
} else {
while((!sortedStack.isEmpty()) && sortedStack.peek() > element) {
stack.push(sortedStack.pop());
}
sortedStack.push(element);
}
}
}
return sortedStack;
}
}