Given a stack S, need to sort the stack using only Push
, Pop
, Top
, IsEmpty
, IsFull
.
Looking for most sim
Sorting a stack without extra space is quite not a possibility . At least not coming to my sane mind . We can surely use the recursion stack as extra space over here . The below approach might be helful .
My approach is O(N**2) . Over here I am iterating over stack N times, every time fixing the ith element in the stack .
Firstly fixed the bottom element by popping out N elements and pushing min_element and in Second try fixed the 2nd element from bottom by popping out N-1 elements and pushing min_element except the one pushed before this And so on .
Refer to the code below for more details .
stack stk;
int sort_util(stack &stk,int n,int mn)
{
if(n==0)
{
stk.push(mn);
return mn;
}
int vl = stk.top();
stk.pop();
int fmin = sort_util(stk,n-1,min(mn,vl));
if(fmin==vl)
return INT_MAX;
else
stk.push(vl);
return fmin;
}
void sort_stack(stack &stk)
{
for(int i=stk.size();i>1;i--)
sort_util(stk,i,stk.top());
}