Skip to content

Commit 4dad447

Browse files
committed
Sort stack using recursion added
1 parent 867c0ab commit 4dad447

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
/*
2+
Problem Statement:
3+
Given a stack, sort the given stack using recursion such that the greatest element is on the top.
4+
*/
5+
6+
#include <bits/stdc++.h>
7+
using namespace std;
8+
9+
void printStack(stack<int> st)
10+
{
11+
while (!st.empty())
12+
{
13+
int x = st.top();
14+
st.pop();
15+
16+
cout << x << " ";
17+
}
18+
19+
return;
20+
}
21+
22+
void insert(stack<int> &st, int temp)
23+
{
24+
// base condition
25+
if (st.size() == 0 || st.top() < temp)
26+
{
27+
st.push(temp);
28+
return;
29+
}
30+
31+
int val = st.top();
32+
st.pop();
33+
34+
insert(st, temp);
35+
st.push(val);
36+
37+
return;
38+
}
39+
40+
void sortStack(stack<int> &st)
41+
{
42+
// base condition
43+
if (st.size() == 0)
44+
return;
45+
46+
int temp = st.top();
47+
st.pop();
48+
49+
// recursion
50+
sortStack(st);
51+
52+
// function to insert element in stack
53+
insert(st, temp);
54+
55+
return;
56+
}
57+
58+
int main()
59+
{
60+
// input number of element in stack
61+
int n;
62+
cout<<"Enter the number of elements : ";
63+
cin >> n;
64+
65+
stack<int> st;
66+
cout<<"Enter the elements : ";
67+
// input stack elements
68+
for (int i = 0; i < n; i++)
69+
{
70+
int x;
71+
cin >> x;
72+
73+
st.push(x);
74+
}
75+
cout<<"After Sorting : ";
76+
// function to sort stack
77+
sortStack(st);
78+
79+
// function to print stack element
80+
printStack(st);
81+
82+
cout << endl;
83+
84+
return 0;
85+
}
86+
87+
/*
88+
Time Complexity: O(N*N)
89+
Space complexity: O(N)
90+
91+
SAMPLE INPUT AND OUTPUT
92+
Enter the number of elements : 10
93+
Enter the elements : 9 2 5 6 0 1 7 3 4 8
94+
After Sorting : 9 8 7 6 5 4 3 2 1 0
95+
*/

0 commit comments

Comments
 (0)