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);
/**/
}
}