Jun 22, 2009

Design an efficient algorithm to sort elements in a stack in either ascending/descending order, using only pop(), top(), push(), isEmpty(), isFull().

Design an efficient algorithm to sort elements in a stack in either ascending/descending order, using only pop(), top(), push(), isEmpty(), isFull(). Do not use any auxiliary stacks or arrays.
foo(stack(int)& s)
{
if(s.empty())
return;
int num=s.top();
s.pop();
foo(s);
bar(s,num);
}

bar(stack& s, int num)
{
if(!s.empty()&& num < s.top())
{
int temp=s.top();
s.pop();
bar(s,num);
s.push(temp);
}
else s.push(num);
}

No comments:

Post a Comment