Write a C program to sort a stack in ascending order.

1,011 views
Skip to first unread message

vijay

unread,
Jul 17, 2010, 9:28:27 AM7/17/10
to Programming Puzzles
Write a C program to sort a stack in ascending order. You should not
make any assumptions about how the stack is implemented. The following
are the only
functions that should be used to write this program:
Push | Pop | Top | IsEmpty | IsFull
The algorithm is O(N^2) and appears below.
Do we have any other better solution which is less than O(n * n) ?

void sort_stack(Stack * src, Stack * dest)
{
while (!src->IsEmpty())
{
Int tmp = src->Pop();
while(!dest->IsEmpty() && dest->Top() > tmp)
{
src->Push(dest->Pop());
}
dest->Push(tmp);
}


}

Srinivas

unread,
Sep 14, 2010, 7:33:48 AM9/14/10
to Programming Puzzles
reverse(stack *s){
IsEmpty(s)
return;
top = pop(s);
reverse(s);
ascending(s, top);

}

ascending(stack *s, int top){
IsEmpty(s){
push(top);
return;
}
i = pop(s);
if(i < top){
ascending(s, top);
push(i);
}
else{
ascending(s, i);
push(top);
Reply all
Reply to author
Forward
0 new messages