您的位置:首页 > 其它

Ch3-6: sorting a stack in an ascending order

2014-01-15 17:49 417 查看
if only use 1 additional stack, then mimic the selection sort.

or with 2 additional stacks, we can mimic merge sort or quick sort.

Full code:

// solution for Ch3-6 by mimicing selection sort
// check CTCI book, it's description is more clear than Hawstein
#include
#include
#include
using namespace std;

stack Ssort(stack s){
stack t;
while(!s.empty()){
int data = s.top();
s.pop();
while(!t.empty() && t.top()>data){ // condition 1 will take several inner loop
s.push(t.top());
t.pop();
}
t.push(data); // condition 2 will take a several outer loop
}
return t;
}

int main(){
srand((unsigned)time(0));
stack s;

for(int i=0; i<10; ++i)
s.push((rand()%100));
s = Ssort(s);
while(!s.empty()){
cout<


Outpu:

Executing the program....
$demo
77 72 71 65 65 43 32 29 10 3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐