分析:
无论是从小到大排序,还是从大到小排序,重要的是按照层次找出最大(最小数)。
数据栈 stack
辅助栈 help
设置游标数cur
每次help中的数比cur大,则弹出,然后再push进cur(小)。
一次循环,也就是help中的都时push进(从小到大的数,即小数压底)。
直到stack弹空,在将help中的数压入stack,便完成了小数先输出的任务(后进先出)
代码如下
public class StackByStackSort {
/**
*通过两个栈如何实现排序
* help实际上是用来存储最大值(最小值)
* 输出结果为从小至大排序
*/
static int i=0;
public static void sortStackByStack(Stack<Integer> stack) {
Stack<Integer> help = new Stack<>();
while(!stack.isEmpty()){
int cur = stack.pop();
//peek是查看栈顶,不弹出,与pop不一样
while(!help.isEmpty() && help.peek()> cur){
stack.push(help.pop());
}
help.push(cur);
//i++;
//System.out.println("help-: "+help.toString());
//System.out.println("stack--: "+stack.toString());
}
while (!help.isEmpty()){
stack.push(help.pop());
}
}
public static void main(String[] args) {
Stack<Integer> s ;
s = new Stack<>();
s.push(1);
s.push(5);
s.push(3);
s.push(4);
s.push(2);
s.push(5);
s.push(3);
sortStackByStack(s);
while(!s.isEmpty()){
System.out.println(s.pop());
}
}
}
时间复杂度
通过测算,一般情况下时间复杂度要明显小于n^2,当然这跟stack中数的混序状态有关,最佳状态为o(n)