Sort a stack using recursion
Given a stack, sort it using recursion. Use of any loop constructs like while, for, etc is not allowed. We can only use the following ADT functions on Stack S:
is_empty(S) : Tests whether stack is empty or not. push(S) : Adds new element to the stack. pop(S) : Removes top element from the stack. top(S) : Returns value of the top element. Note that this function does not remove element from the stack.
Input: -3 <--- Top 14 18 -5 30 Output: 30 <--- Top 18 14 -3 -5
This problem is mainly a variant of Reverse stack using recursion.
The idea of the solution is to hold all values in Function Call Stack until the stack becomes empty. When the stack becomes empty, insert all held items one by one in sorted order. Here sorted order is important.
We can use the below algorithm to sort stack elements:
sortStack(stack S) if stack is not empty: temp = pop(S); sortStack(S); sortedInsert(S, temp);
Below algorithm is to insert elements in sorted order: