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:
Outpu:
Executing the program....
$demo
77 72 71 65 65 43 32 29 10 3
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
相关文章推荐
- Q3.6 sort a stack in ascending order
- 【18】Sort a stack in ascending order
- Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
- Ruby: Sorting an array of strings, in alphabetical order, that includes some arrays of strings
- Ch3-4: solve Hanoi in C++ with recursion, and with stack explicitly
- How can I connect Unity to an SQL database in order to implement an MMO?
- In order to use an interrupt in a Cortex-M3/M4, you need the following
- 【Angular2】You have to be inside an angular-cli project in order to use the generate command
- Understand Your Project Costs in an Engineer-to-Order Manufacturing Environment
- U3D sorting layer, sort order, order in layer, layer深入辨析
- 【angular】you have to be inside an Angular CLI project in order to use the serve command
- [转]Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application (3 of 10)
- stackover flow 上的一个问题:Find the most common entry in an array
- Data Structure Binary Tree: Inorder Tree Traversal without recursion and without stack!
- 执行foreach时出现An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll的错误查解
- Given an in-order traversal only for a binary tree (not necessarily a BST), …
- HOW TO: Find the Problem Exception Stack When You Receive an UnhandledExceptionFilter Call in the St
- How do you copy the contents of an array to a std::vector in C++ without looping? (From stack over flow)
- Judging if an array is ascendingin a recursion way
- HOW TO: Find the Problem Exception Stack When You Receive an UnhandledExceptionFilter Call in the St