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