Skip to content

Commit 149a56f

Browse files
committed
stacksort
1 parent f8326e7 commit 149a56f

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

Recursion/sort_a_stack.cpp

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
// { Driver Code Starts
2+
3+
/*
4+
Sort a stack
5+
Easy Accuracy: 50.51% Submissions: 46307 Points: 2
6+
Given a stack, the task is to sort it such that the top of the stack has the greatest element.
7+
8+
Example 1:
9+
10+
Input:
11+
Stack: 3 2 1
12+
Output: 3 2 1
13+
Example 2:
14+
15+
Input:
16+
Stack: 11 2 32 3 41
17+
Output: 41 32 11 3 2
18+
Your Task:
19+
You don't have to read input or print anything. Your task is to complete the function sort() which sorts the elements present in the given stack. (The sorted stack is printed by the driver's code by popping the elements of the stack.)
20+
21+
Expected Time Complexity : O(N*N)
22+
Expected Auixilliary Space : O(N) recursive.
23+
24+
Constraints:
25+
1<=N<=100
26+
*/
27+
28+
#include<bits/stdc++.h>
29+
using namespace std;
30+
31+
class SortedStack{
32+
public:
33+
stack<int> s;
34+
void sort();
35+
};
36+
37+
void printStack(stack<int> s)
38+
{
39+
while (!s.empty())
40+
{
41+
printf("%d ", s.top());
42+
s.pop();
43+
}
44+
printf("\n");
45+
}
46+
47+
int main()
48+
{
49+
int t;
50+
cin>>t;
51+
while(t--)
52+
{
53+
SortedStack *ss = new SortedStack();
54+
int n;
55+
cin>>n;
56+
for(int i=0;i<n;i++)
57+
{
58+
int k;
59+
cin>>k;
60+
ss->s.push(k);
61+
}
62+
ss->sort();
63+
printStack(ss->s);
64+
}
65+
}// } Driver Code Ends
66+
67+
68+
/*The structure of the class is
69+
class SortedStack{
70+
public:
71+
stack<int> s;
72+
void sort();
73+
};
74+
*/
75+
76+
/* The below method sorts the stack s
77+
you are required to complete the below method */
78+
79+
void insert(stack<int>&s, int x){
80+
if(s.empty()||s.top()<x){
81+
s.push(x);
82+
return;
83+
}
84+
int y = s.top();
85+
s.pop();
86+
insert(s, x);
87+
s.push(y);
88+
}
89+
void SortedStack :: sort()
90+
{
91+
//Your code here
92+
if(s.size() == 1){
93+
return;
94+
}
95+
int x = s.top();
96+
s.pop();
97+
sort();
98+
insert(s,x);
99+
}
100+
{"mode":"full","isActive":false}

0 commit comments

Comments
 (0)