forked from AaqilSh/DSA-Collection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecursiveSolutionToSortAStack.cpp
78 lines (62 loc) · 1.59 KB
/
RecursiveSolutionToSortAStack.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
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
// Insert the given key into the sorted stack while maintaining its sorted order.
// This is similar to the recursive insertion sort routine
void sortedInsert(stack<int> &stack, int key)
{
// base case: if the stack is empty or
// the key is greater than all elements in the stack
if (stack.empty() || key > stack.top())
{
stack.push(key);
return;
}
/* We reach here when the key is smaller than the top element */
// remove the top element
int top = stack.top();
stack.pop();
// recur for the remaining elements in the stack
sortedInsert(stack, key);
// insert the popped element back into the stack
stack.push(top);
}
// Recursive method to sort a stack
void sortstack(stack<int> &stack)
{
// base case: stack is empty
if (stack.empty()) {
return;
}
// remove the top element
int top = stack.top();
stack.pop();
// recur for the remaining elements in the stack
sortstack(stack);
// insert the popped element back into the sorted stack
sortedInsert(stack, top);
}
void printStack(stack<int> stack)
{
while (!stack.empty())
{
cout << stack.top() << " ";
stack.pop();
}
cout << endl;
}
int main()
{
vector<int> list = { 5, -2, 9, -7, 3 };
stack<int> stack;
for (int i: list) {
stack.push(i);
}
cout << "Stack before sorting: ";
printStack(stack);
sortstack(stack);
cout << "Stack after sorting: ";
printStack(stack);
return 0;
}