两个栈(数据栈+空栈)如何实现排序?

分析:
无论是从小到大排序,还是从大到小排序,重要的是按照层次找出最大(最小数)。
数据栈 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)

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值