forked from Astha369/CPP_Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsortstack.cpp
48 lines (41 loc) · 811 Bytes
/
sortstack.cpp
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
#include<iostream>
#include<stack>
using namespace std;
void insertSorted(stack<int>& s, int target){
//base case
if(s.empty() || (!s.empty() && s.top()>target)){
s.push(target);
return;
}
int topElement=s.top();
s.pop();
insertSorted(s,target);
//backtracking
s.push(topElement);
}
void sortStack(stack<int>&s){
//base case
if(s.empty()){
return;
}
int topElement=s.top();
s.pop();
sortStack(s);
insertSorted(s,topElement);
}
int main(){
stack<int>st;
st.push(22);
st.push(3);
st.push(10);
st.push(2);
st.push(413);
st.push(9);
sortStack(st);
cout<<"Print stack after sorting"<<endl;
while(!st.empty()){
cout<<st.top()<<" ";
st.pop();
}
cout<<endl;
}