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<
<<" "; s.pop(); } return 0; }
Outpu:
Executing the program....
$demo
77 72 71 65 65 43 32 29 10 3