Given a stack of integers st[], sort the stack in ascending order such that the largest element is at the top and the smallest element is at the bottom.
Example:
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.
Input: st[] = [3, 2, 1] Output: [3, 2, 1] Explanation: The stack is already sorted in ascending order.
Using an Auxiliary Stack - O(n^2) Time and O(n) Auxiliary Space
We use a temporary stack to maintain sorted items. We take the top items one by one from given stack and put it at right place in temp.
Create an empty auxiliary stack temp.
Pop the top element from st and store it in a variable x.
While temp is not empty and its top element is smaller than x, move the top element of temp back to st.
Push x into temp.
Repeat the above steps until all elements from st are processed.
Finally, move all elements from temp back to st.
Since temp maintains the elements in sorted order, the final stack has the largest element at the top and the smallest element at the bottom.
C++
#include<bits/stdc++.h>usingnamespacestd;voidsortStack(stack<int>&st){stack<int>temp;while(!st.empty()){intx=st.top();st.pop();// Move smaller elements back to stwhile(!temp.empty()&&temp.top()<x){st.push(temp.top());temp.pop();}temp.push(x);}// Move sorted elements back to stwhile(!temp.empty()){st.push(temp.top());temp.pop();}}intmain(){stack<int>st;st.push(11);st.push(2);st.push(32);st.push(3);st.push(41);sortStack(st);cout<<"[";// Print stack from top to bottomwhile(!st.empty()){cout<<st.top();st.pop();if(!st.empty())cout<<", ";}cout<<"]";return0;}
Java
importjava.util.Stack;classGFG{staticvoidsortStack(Stack<Integer>st){Stack<Integer>temp=newStack<>();while(!st.isEmpty()){intx=st.pop();// Move smaller elements back to stwhile(!temp.isEmpty()&&temp.peek()<x){st.push(temp.pop());}temp.push(x);}// Move sorted elements back to stwhile(!temp.isEmpty()){st.push(temp.pop());}}publicstaticvoidmain(String[]args){Stack<Integer>st=newStack<>();st.push(11);st.push(2);st.push(32);st.push(3);st.push(41);sortStack(st);System.out.print("[");while(!st.isEmpty()){System.out.print(st.pop());if(!st.isEmpty()){System.out.print(", ");}}System.out.print("]");}}
Python
defsortStack(st):temp=[]whilest:x=st.pop()# Move smaller elements back to stwhiletempandtemp[-1]<x:st.append(temp.pop())temp.append(x)# Move sorted elements back to stwhiletemp:st.append(temp.pop())if__name__=="__main__":st=[]st.append(11)st.append(2)st.append(32)st.append(3)st.append(41)sortStack(st)print("[",end="")whilest:print(st.pop(),end="")ifst:print(", ",end="")print("]")
C#
usingSystem;usingSystem.Collections.Generic;classGFG{staticvoidsortStack(Stack<int>st){Stack<int>temp=newStack<int>();while(st.Count>0){intx=st.Pop();// Move smaller elements back to stwhile(temp.Count>0&&temp.Peek()<x){st.Push(temp.Pop());}temp.Push(x);}// Move sorted elements back to stwhile(temp.Count>0){st.Push(temp.Pop());}}publicstaticvoidMain(){Stack<int>st=newStack<int>();st.Push(11);st.Push(2);st.Push(32);st.Push(3);st.Push(41);sortStack(st);Console.Write("[");while(st.Count>0){Console.Write(st.Pop());if(st.Count>0){Console.Write(", ");}}Console.Write("]");}}
JavaScript
classStack{constructor(){this.st=[];}push(x){this.st.push(x);}pop(){returnthis.st.pop();}top(){returnthis.st[this.st.length-1];}empty(){returnthis.st.length===0;}}functionsortStack(st){lettemp=newStack();while(!st.empty()){letx=st.top();st.pop();// Move smaller elements back to stwhile(!temp.empty()&&temp.top()<x){st.push(temp.top());temp.pop();}temp.push(x);}// Move sorted elements back to stwhile(!temp.empty()){st.push(temp.top());temp.pop();}}// Driver codeletst=newStack();st.push(11);st.push(2);st.push(32);st.push(3);st.push(41);sortStack(st);letans=[];while(!st.empty()){ans.push(st.top());st.pop();}console.log("["+ans.join(", ")+"]");
Output
[41, 32, 11, 3, 2]
Using Recursion - O(n^2) Time and O(n) Auxiliary Space
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.
We use two functions:
sortStack() removes elements from the stack and recursively sorts the remaining elements.
sortedInsert() inserts a removed element into its correct position in the sorted stack.
Steps
Remove the top element from the stack and store it in x.
Recursively call sortStack() to sort the remaining stack.
Once the remaining stack is sorted, call sortedInsert() to place x at its correct position.
In sortedInsert(), if the stack is empty or its top element is smaller than or equal to x, push x.
Otherwise, temporarily remove the top element and recursively find the correct position for x.
After inserting x, push the temporarily removed elements back.
This process continues until all elements are placed in their correct positions.
As a result, the largest element is at the top and the smallest element is at the bottom.
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);cout<<"[";// Print stack from top to bottomwhile(!st.empty()){cout<<st.top();st.pop();if(!st.empty())cout<<", ";}cout<<"]";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);System.out.print("[");while(!st.isEmpty()){System.out.print(st.pop());if(!st.isEmpty()){System.out.print(", ");}}System.out.print("]");}}
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)print("[",end="")whilest:print(st.pop(),end="")ifst:print(", ",end="")print("]")
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());if(st.Count>0){Console.Write(", ");}}Console.Write("]");}}
JavaScript
classStack{constructor(){this.st=[];}push(x){this.st.push(x);}pop(){returnthis.st.pop();}top(){returnthis.st[this.st.length-1];}empty(){returnthis.st.length===0;}}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);letans=[];while(!st.empty()){ans.push(st.top());st.pop();}console.log("["+ans.join(", ")+"]");