-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Sort_stack_using_recursion.cpp
106 lines (76 loc) · 1.3 KB
/
Sort_stack_using_recursion.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
Problem Statement:
Given a stack, sort the given stack using recursion such that the greatest element is on the top.
*/
#include <bits/stdc++.h>
using namespace std;
void printStack(stack<int> st)
{
while (!st.empty())
{
int x = st.top();
st.pop();
cout << x << " ";
}
return;
}
void insert(stack<int> &st, int temp)
{
// base condition
if (st.size() == 0 || st.top() < temp)
{
st.push(temp);
return;
}
int val = st.top();
st.pop();
insert(st, temp);
st.push(val);
return;
}
void sortStack(stack<int> &st)
{
// base condition
if (st.size() == 0)
return;
int temp = st.top();
st.pop();
// recursion
sortStack(st);
// function to insert element in stack
insert(st, temp);
return;
}
int main()
{
// input number of element in stack
int n;
cin >> n;
stack<int> st;
// input stack elements
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
st.push(x);
}
// function to sort stack
sortStack(st);
// function to print stack element
printStack(st);
cout << endl;
return 0;
}
/*
Time Complexity: O(N*N)
Space complexity: O(N)
*/
/*
Test Case:
Input: 10
9 2 5 6 0 1 7 3 4 8
OutPut: 9 8 7 6 5 4 3 2 1 0
Input: 5
11 2 32 3 41
Output: 41 32 11 3 2
*/