-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort-stack.cpp
60 lines (51 loc) · 1.01 KB
/
sort-stack.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
#include <iostream>
#include <stack>
using namespace std;
void CompareValue(stack<int> &St, int value)
{
if (St.empty() || St.top() < value)
{
St.push(value);
return;
}
else
{
int temp = St.top();
St.pop();
CompareValue(St, value);
St.push(temp);
}
}
void sort(stack<int> &St)
{
if (St.empty())
{
return; // Base case: stack is already sorted or empty
}
int temp = St.top();
St.pop();
sort(St); // Recursively sort the remaining stack
CompareValue(St, temp); // Insert the popped element in its correct place
}
int main() {
// unsorted stack
stack<int> St;
St.push(5);
St.push(1);
St.push(3);
St.push(2);
St.push(4);
// sorted stack
sort(St);
if (St.empty()) {
cout << "Exception";
exit(1);
}
// print sorted stack
cout << "Sorted stack: ";
while (!St.empty()) {
cout << St.top() << " ";
St.pop();
}
return 0;
}