分别是利用一个辅助栈和两个辅助栈
public class StackSort {
public static void sortWithOneCache(Stack<Integer> stack) {
if (stack == null || stack.isEmpty()) {
return;
}
Stack<Integer> cache = new Stack<Integer>();
while (!stack.isEmpty()) {
int tmp = stack.pop();
while (!cache.isEmpty() && tmp < cache.peek()) {
stack.push(cache.pop());
}
cache.push(tmp);
}
while (!cache.isEmpty()) {
stack.push(cache.pop());
}
}
public static void sortWithTwoCache(Stack<Integer> stack) {
if (stack == null || stack.isEmpty()) {
return;
}
Stack<Integer> cache1 = new Stack<Integer>();
Stack<Integer> cache2 = new Stack<Integer>();
while (!stack.isEmpty()) {
int tmp = stack.pop();
while (!cache1.isEmpty() && tmp < cache1.peek()) {
cache2.push(cache1.pop());
}
cache1.push(tmp);
while (!cache2.isEmpty()) {
cache1.push(cache2.pop());
}
}
while (!cache1.isEmpty()) {
stack.push(cache1.pop());
}
}
}