What is the best method to sort the stack in ascending order? I ran into this interview question, and I ran into some problems for a better and effective solution.
There are two methods that I can think of.
To print the entire contents of the stack and store them in an array, and then sort the array into
O(nLog n)
, and then push the contents back O(nLog n)
stack. Not the best way ...
Recursive stack implementation for sorting it
void sort(stack) { type x; if (!isEmpty(stack)) { x = pop(stack); sort(stack); insert(x, stack); } } void insert(x, stack) { type y; if (!isEmpty(stack) && top(stack) < x) { y = pop(stack); insert(x, stack); push(y, stack); } else { push(x, stack); } }
But the second way seems to cause too many recursive calls, and overhead will be a problem if the stack turns out to be really big.
Is it possible to solve this problem much better for better spatial and temporal complexity?
There are so many recursive calls (overlapping subtasks), is this a candidate for the type of dynamic programming
problems?
What would be the best way to solve this problem?
source share