Input: st[] = [41, 3, 32, 2, 11] Output: [41, 32, 11, 3, 2] Explanation: After sorting, the smallest element (2) is at the bottom and the largest element (41) is at the top.
We use recursion to sort the stack without relying on extra data structures. The approach will be:
Remove the top element of the stack.
Recursively sort the remaining stack.
Insert the removed element back into the stack in its correct sorted position.
How Recursion Works
Remove the top element of the stack and hold it temporarily.
Recursively sort the remaining stack, which is now smaller (it has one fewer element).
Once the smaller stack is sorted, insert the held element back into its correct position: If the stack is empty or the top element is smaller than the held element, push it directly. Otherwise, remove the top element, recursively find the correct position for the held element, and then push back the removed element.
Repeat this process as recursion unwinds until all elements are sorted in ascending order, with the smallest at the bottom and the largest at the top.
Output
41 32 11 3 2
Time Complexity: O(n2) Auxiliary Space: O(n), due to call stack.