I am using two more helper stacks to sort. Kindly suggest improvements in terms of space and time.
import java.util.ArrayDeque;
import java.util.Deque;
public class SortStackAscendingOrder {
Deque<Integer> stackhelper1 = new ArrayDeque<>();
Deque<Integer> stackHelper2 = new ArrayDeque<>();
public Deque<Integer> sortStack(Deque<Integer> mainStack) {
if (mainStack.isEmpty()) {
return null;
}
while (!mainStack.isEmpty()) {
int mainItem = mainStack.pop();
int helperItem1 = -1;
if (!stackhelper1.isEmpty()) {
helperItem1 = stackhelper1.peek();
}
if (mainItem > helperItem1) {
// push all helperItem1 to helperItem2, till it is in ascending
// order
while (!stackhelper1.isEmpty() && mainItem > helperItem1) {
stackHelper2.push(stackhelper1.pop());
helperItem1 = stackhelper1.peek();
}
// push mainItem.
stackhelper1.push(mainItem);
// bring back all the helperItem2
while (!stackHelper2.isEmpty()) {
stackhelper1.push(stackHelper2.pop());
}
} else {
// directly push in stackhelper1
stackhelper1.push(mainItem);
}
}
return stackhelper1;
}
}