stack排序
Cracking Interview 3-6
用的書上的思路,O(n^2)的時間復雜度。
#include <iostream> #include <stack> using namespace std;stack<int> sort(stack<int> unorderStack) {stack<int> orderStack;stack<int> tmpStack;while(!unorderStack.empty()){int value = unorderStack.top();if (orderStack.empty())orderStack.push(value);else if (value < orderStack.top())orderStack.push(value);else {while (!orderStack.empty() && value > orderStack.top()){tmpStack.push(orderStack.top());orderStack.pop();}orderStack.push(value);while (!tmpStack.empty()){orderStack.push(tmpStack.top());tmpStack.pop();}}unorderStack.pop();}return orderStack; }int main() {stack<int> stk;for (int i = 0; i < 10; i++){int value = rand()%150;cout<<"Pushing : "<<value<<endl;stk.push(value);}cout<<"sorting ..."<<endl;stk = sort(stk);cout<<"sort complete"<<endl;while (!stk.empty()){cout<<stk.top()<<endl;stk.pop();}return 0; }?
?
?
?
EOF
轉載于:https://www.cnblogs.com/lihaozy/archive/2012/12/09/2809866.html
總結
- 上一篇: Myeclipse出现 java文件中文
- 下一篇: 2012年面试题集