Related: Sorting a given stack using one additional stack
Sort a stack using recursion - GeeksforGeeks
Given a stack, sort it using recursion. Use of any loop constructs like while, for..etc is not allowed.
Read full article from Sort a stack using recursion - GeeksforGeeks
Sort a stack using recursion - GeeksforGeeks
Given a stack, sort it using recursion. Use of any loop constructs like while, for..etc is not allowed.
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.
sortStack(stack S) if stack is not empty: temp = pop(S); sortStack(S); sortedInsert(S, temp);
Below algorithm is to insert element is sorted order:
sortedInsert(Stack S, element) if stack is empty OR element > top element push(S, elem) else temp = pop(S) sortedInsert(S, element) push(S, temp)