Given a stack of integers st[], Sort the stack in ascending order (smallest element at the bottom and largest at the top).
Example:
Input: st[] = [1, 2, 3] Output: [3, 2, 1] Explanation: The stack is already sorted in ascending order.
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.
[Approach] Using Recursion
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.
C++
#include<iostream>#include<stack>usingnamespacestd;// Insert element into sorted stackvoidsortedInsert(stack<int>&st,intx){// If stack is empty or// top element is smaller, push xif(st.empty()||st.top()<=x){st.push(x);return;}inttop=st.top();st.pop();// Recursively insert x in sorted ordersortedInsert(st,x);st.push(top);}// Sort the stack recursivelyvoidsortStack(stack<int>&st){if(st.empty())return;inttop=st.top();st.pop();// Recursively sort the remaining stacksortStack(st);sortedInsert(st,top);}intmain(){stack<int>st;st.push(41);st.push(3);st.push(32);st.push(2);st.push(11);sortStack(st);while(!st.empty()){cout<<st.top()<<" ";st.pop();}return0;}
Java
importjava.util.Stack;classGfG{// Insert element into sorted stackstaticvoidsortedInsert(Stack<Integer>st,intx){// If stack is empty or// top element is smaller, push xif(st.isEmpty()||st.peek()<=x){st.push(x);return;}inttop=st.pop();// Recursively insert x in sorted ordersortedInsert(st,x);st.push(top);}// Sort the stack recursivelystaticvoidsortStack(Stack<Integer>st){if(st.isEmpty())return;inttop=st.pop();// Recursively sort the remaining stacksortStack(st);sortedInsert(st,top);}publicstaticvoidmain(String[]args){Stack<Integer>st=newStack<>();st.push(41);st.push(3);st.push(32);st.push(2);st.push(11);sortStack(st);while(!st.isEmpty()){System.out.print(st.pop()+" ");}}}
Python
# Insert element into sorted stackdefsortedInsert(st,x):# If stack is empty or# top element is smaller, push xifnotstorst[-1]<=x:st.append(x)returntop=st.pop()# Recursively insert x in sorted ordersortedInsert(st,x)st.append(top)# Sort the stack recursivelydefsortStack(st):ifnotst:returntop=st.pop()# Recursively sort the remaining stacksortStack(st)sortedInsert(st,top)if__name__=="__main__":st=[41,3,32,2,11]sortStack(st)whilest:print(st.pop(),end=" ")
C#
usingSystem;usingSystem.Collections.Generic;classGfG{// Insert element into sorted stackstaticvoidsortedInsert(Stack<int>st,intx){// If stack is empty// or top element is smaller, push xif(st.Count==0||st.Peek()<=x){st.Push(x);return;}inttop=st.Pop();// Recursively insert x in sorted ordersortedInsert(st,x);st.Push(top);}// Sort the stack recursivelystaticvoidsortStack(Stack<int>st){if(st.Count==0)return;inttop=st.Pop();// Recursively sort the remaining stacksortStack(st);sortedInsert(st,top);}staticvoidMain(){Stack<int>st=newStack<int>();st.Push(41);st.Push(3);st.Push(32);st.Push(2);st.Push(11);sortStack(st);while(st.Count>0){Console.Write(st.Pop()+" ");}}}
JavaScript
functionsortedInsert(st,x){// If stack is empty or // top element is smaller, push xif(st.length===0||st[st.length-1]<=x){st.push(x);return;}lettop=st.pop();// Recursively insert x in sorted ordersortedInsert(st,x);st.push(top);}functionsortStack(st){if(st.length===0)return;lettop=st.pop();// Recursively sort the remaining stacksortStack(st);sortedInsert(st,top);}// Driver Codeletst=[];st.push(41);st.push(3);st.push(32);st.push(2);st.push(11);sortStack(st);letres=[];while(st.length>0){res.push(st.pop());}console.log(res.join(" "));
Output
41 32 11 3 2
Time Complexity: O(n2) Auxiliary Space: O(n), due to call stack.