Given a stack, sort it using recursion. The use of any other data structures (like containers in STL or Collections in Java) is not allowed.

For example,

Stack before sorting : 5 | -2 | 9 | -7 | 3    where 3 is the top element
Stack after sorting  : -7 | -2 | 3 | 5 | 9    where 9 is the top element

Practice this problem

The idea is simple – recursively remove values from the stack until the stack becomes empty and then insert those values (from the call stack) back into the stack in a sorted position.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

Stack before sorting: 3 -7 9 -2 5
Stack after sorting: 9 5 3 -2 -7

Java


Download  Run Code

Output:

Stack before sorting: [5, -2, 9, -7, 3]
Stack after sorting: [-7, -2, 3, 5, 9]

Python


Download  Run Code

Output:

Stack before sorting: [5, -2, 9, -7, 3]
Stack after sorting: [-7, -2, 3, 5, 9]

The time complexity of the above solution is O(n2) and requires O(n) implicit space for the call stack, where n is the total number of elements in the stack.