Cracking coding interview(3.6)堆栈排序

3.6 Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.

explanation:

1.使用插入法,利用另一个栈s2,将当前栈的元素插入到另一个栈,并返回最终保存按升序排列的元素的栈s2。

2.若s2栈遇到小于当前插入值得元素,将该元素从s2栈弹出,压入s1栈。

most worst Time complexity:already ordered by ascending

assume Stack s with n elements

executive time == (1+3+5+...+2n-1) == n^2

3.若用其他排序算法,则可达到O(nlogn),流程如下:

(1.pop出所有元素

(2.排序

(3.push入栈并返回该栈

import java.util.Stack;

public class Solution{
	public static Stack<Integer> sortStack(Stack<Integer> s){
		Stack<Integer> s2 = new Stack<Integer>();
		while(!s.empty()){
			Integer n = s.pop(), n2 = null;
			while(!s2.empty()){
				n2 = s2.peek();
				if(n.compareTo(n2) <= 0)
					break;
				else
					s.push(s2.pop());
			}
			s2.push(n);	
		}
		return s2;
	}
	public static void printStack(Stack<Integer> s){
		while(!s.empty())
			System.out.print(s.pop()+" ");
		System.out.println();	
	}
	public static void main(String[] args){
		Stack<Integer> s = new Stack<Integer>();
		//descending at first, most worst case:
		//time complexity:O(n)
		for(int i=1;i <= 20;i++)
			s.push(i);
//		Solution.printStack(s);
		s = Solution.sortStack(s);
		Solution.printStack(s);
		
		System.out.println();
		/**/
		//asending at first,most best case:
		//time complexity:O(n^n)
		for(int i=20;i >= 1;i--)
			s.push(i);
//		Solution.printStack(s);
		s = Solution.sortStack(s);
		Solution.printStack(s);
		/**/
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值