您的位置:首页 > 编程语言 > Java开发

fw 3.6 - stack sort- java version - 2013年12月16日23:23:32

2013-12-17 12:22 363 查看
package test_kepler;

import java.util.Stack;

public class StackSort { 
	
	Stack<Integer> o_stack;
	Stack<Integer> b_stack;
	Stack<Integer> r_stack;
	public StackSort()
	{
		o_stack = new Stack<Integer>();
		b_stack = new Stack<Integer>();
		r_stack = new Stack<Integer>();
	}
	public void push(int i)
	{
		o_stack.push(i);
	}
	public int pop()
	{
		return o_stack.pop();
	}
	//o_stack<->r_stack;
	public void sort_stack()
	{
		int i = 0;
		while(o_stack.size()!= 0 || b_stack.size()!= 0)
		{
			++i;
			int min = 0;
			if(o_stack.size()!=0)
			{//o_stack->b_stack;
				min = o_stack.pop();
				while(o_stack.size()!=0)
				{
					int t = o_stack.pop();
					if(t>min)
						{
							b_stack.push(t);
						}
					else
						{
							b_stack.push(min);
							min = t;
						}
				}
				r_stack.push(min);
			}
			else
			{//b_stack->o_stack
				if(b_stack.size()!=0)
				{
					min = b_stack.pop();
					while(b_stack.size()!=0)
					{
						int t = b_stack.pop();
						if(t>min)
							{
								o_stack.push(t);
							}
						else
							{
								o_stack.push(min);
								min = t;
							}
					}
					r_stack.push(min);
				}			
			}
		}
		
		o_stack=r_stack;
		
	}
	// standard solution
	public static Stack<Integer> sort(Stack<Integer> s) {
		 Stack<Integer> r = new Stack<Integer>();
		 while(!s.isEmpty()) {
		 int tmp = s.pop();
		 while(!r.isEmpty() && r.peek() > tmp) {
		 s.push(r.pop());
		 }
		 r.push(tmp);
		 }
		 return r;
		 }
	
	public static void main(String[] args)
	{
		StackSort ss = new StackSort();
		 int a[] = {1,23,-2,-43,-243,-33,3332};
		 for(int i = 0;i<7;++i)
		 {
			 ss.push(a[i]);
		 }
		 ss.sort_stack();
		 
		 for(int i = 0;i<7;++i)
		 {
			 System.out.println(ss.pop());
		 }
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: