-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStack_sorting_using_tempStack.cpp
More file actions
56 lines (48 loc) · 966 Bytes
/
Stack_sorting_using_tempStack.cpp
File metadata and controls
56 lines (48 loc) · 966 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
49
50
51
52
53
54
55
#include<iostream>
#include<stack>
using namespace std;
int main()
{
//n=no. of elements in stack
//el=element of stacks
int n, el;
//declaring two stacks original & temporary
stack<int> ostack /* original stack */, tstack /* temporary stack */;
cout<<"\n Enter No. of elements of stack"<<endl;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>el;
ostack.push(el);
}
//sorting stack
while(!ostack.empty())
{
int k=ostack.top();
ostack.pop();
while(!tstack.empty() && tstack.top()<k)
{
/*
minimum elements remains on the top of sorted stack
k=4
elements will pop from temporary stack if
top elements of stack is smaller than 4
|3|
|2|
|8|
in above example elements will pop upto 2
since 3 & 2 are smaller than 4
*/
ostack.push(tstack.top());
tstack.pop();
}
tstack.push(k);
}
while(!tstack.empty())
{
cout<<tstack.top()<<" ";
tstack.pop();
}
cout<<endl;
return 0;
}