Here are the constraints :
- Only STL must be used for stack creation (do not use struct to create stack)
- Sort the stack without using any loops
I have figured out the solution with constraint 2. But when I create a stack using STL to satisfy constraint 1, the stack is not getting sorted and the output is just same as the input.
Expected Output : 5 4 3 2 1 My Output : 1 2 4 3 5
Below is the code :
#include<iostream>
#include<stack>
using namespace std;
void SortedInsert(stack<int> S,int x)
{
if(S.empty() || x > S.top())
S.push(x);
else
{
int temp = S.top();
S.pop();
SortedInsert(S,x);
S.push(temp);
}
}
void StackSort(stack<int> S)
{
if(!S.empty())
{
int x = S.top();
S.pop();
StackSort(S);
SortedInsert(S,x);
}
}
void main()
{
int arr[5] = {1,2,4,3,5};
stack<int> S;
for(int i=4 ; i>=0 ; i--)
S.push(arr[i]);
StackSort(S);
while(!S.empty())
{
cout<<S.top()<<" ";
S.pop();
}
cin.get();
}