My program is supposed to sort a stack such that the smallest item are on the top. I can use a temporary stack, but you may not copy the elements into any other data structure. The program works overall, but I was wondering if there is anything that I can do to make it more efficient/better.
import java.util.Stack;
public class SortStack {
Stack sorted;
public Stack sort(Stack unsorted) {
int temp2 = 0; // to keep track of number of top of the sorted stack
while(!unsorted.isEmpty()) {
int temp1 = (int) unsorted.pop();
if(sorted == null) { // if sorted stack is empty, create it and push the first number onto it
sorted = new Stack();
sorted.push(temp1);
System.out.println(temp1 + " pushed from s1 to s2");
} else if(temp1 >= temp2) { // push onto sorted stack if what is popped from original stack >= unsorted stack
sorted.push(temp1);
temp2 = temp1;
System.out.println(temp1 + " pushed from s1 to s2");
} else { // keep on popping from sorted stack to unsorted stack until unsortedTop < sortedTop
// this will make sure whatever is popped from original stack will not be less than the peek of the sorted stack
while(temp1 < temp2) {
int sortedPop = (int) sorted.pop();
unsorted.push(sortedPop);
System.out.println(sortedPop + " pushed from s2 to s1");
temp2 = (int) sorted.peek();
}
sorted.push(temp1); // after both stacks are balanced, push element to sorted stack
System.out.println(temp1 + " pushed from s1 to s2");
}
}
return sorted;
}
public static void main(String[] args) {
SortStack ss = new SortStack();
Stack unsorted = new Stack();
unsorted.push(7);
unsorted.push(10);
unsorted.push(5);
unsorted.push(12);
unsorted.push(8);
unsorted.push(3);
unsorted.push(1);
ss.sort(unsorted);
}
}