-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstacksort.cpp
More file actions
48 lines (41 loc) · 841 Bytes
/
stacksort.cpp
File metadata and controls
48 lines (41 loc) · 841 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//sort the given stack using only one temporary stack
#include <iostream>
#include <stack>
using namespace std;
void stack_sort(stack<int> &s)
{
stack<int> temp;
while (!s.empty())
{
int popped_ele = s.top();
s.pop();
while (!temp.empty() && popped_ele < temp.top()) //ascending order
{
s.push(temp.top());
temp.pop();
}
temp.push(popped_ele);
}
while (!temp.empty())
{
s.push(temp.top());
temp.pop();
}
} //O(n^2)
int main()
{
stack<int> s;
s.push(100);
s.push(20);
s.push(10);
s.push(30);
s.push(90);
stack_sort(s);
stack<int> tmpStack = s;
cout << "Sorted numbers are:\n";
while (!tmpStack.empty())
{
cout << tmpStack.top() << " ";
tmpStack.pop();
}
}