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

来源:互联网 发布:java在线考试系统源码 编辑:程序博客网 时间:2024/04/28 19:55
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_stackif(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 solutionpublic 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()); }}}

0 0