Sort a Stack using Recursion Last Updated : 26 Apr, 2025 Comments Improve Suggest changes Like Article Like Report Given a stack, the task is to sort it using recursion.Example: Input: [3 2 1]Output: [3 2 1]Explanation: The given stack is sorted know 3 > 2 > 1Input: [11 2 32 3 41]Output: [41 32 11 3 2]The main idea is to repeatedly pop elements from the stack and sort the remaining stack. After sorting the rest of the stack, the popped element is inserted into its correct position using the sortedInsert function. The sortedInsert function ensures that the element is placed in the correct position in the already sorted stack. This process continues recursively until the stack is fully sorted in ascending order.How does sortedInsert() Work? This function again uses recursion. If stack is empty or top of the stack is smaller, we push the item at the topElse we remove the top item and call sortedInsert recursively for the remaining stack and current item. This ensures that all greater values are held in the function call stack.We finally push the removed the top item back into the stack. This moves all the items held in function call stack into the given stack. C++ #include <iostream> #include <stack> using namespace std; void sortedInsert(stack<int> &s, int x) { if (s.empty() || x > s.top()) { s.push(x); return; } int temp = s.top(); s.pop(); sortedInsert(s, x); s.push(temp); } void sort(stack<int> &s) { if (!s.empty()) { int x = s.top(); s.pop(); sort(s); sortedInsert(s, x); } } int main() { stack<int> s; s.push(11); s.push(2); s.push(32); s.push(3); s.push(41); sort(s); while (!s.empty()) { cout << s.top() << " "; s.pop(); } cout << endl; return 0; } Java import java.util.Stack; public class GfG { public static void sortedInsert(Stack<Integer> s, int x) { if (s.isEmpty() || x > s.peek()) { s.push(x); return; } int temp = s.pop(); sortedInsert(s, x); s.push(temp); } public static void sort(Stack<Integer> s) { if (!s.isEmpty()) { int x = s.pop(); sort(s); sortedInsert(s, x); } } public static void main(String[] args) { Stack<Integer> s = new Stack<>(); s.push(11); s.push(2); s.push(32); s.push(3); s.push(41); sort(s); while (!s.isEmpty()) { System.out.print(s.pop() + " "); } System.out.println(); } } Python def sorted_insert(s, x): if not s or x > s[-1]: s.append(x) return temp = s.pop() sorted_insert(s, x) s.append(temp) def sort(s): if s: x = s.pop() sort(s) sorted_insert(s, x) if __name__ == '__main__': s = [] s.append(11) s.append(2) s.append(32) s.append(3) s.append(41) sort(s) while s: print(s.pop(), end=' ') print() C# using System; using System.Collections.Generic; class GfG { static void SortedInsert(Stack<int> s, int x) { if (s.Count == 0 || x > s.Peek()) { s.Push(x); return; } int temp = s.Pop(); SortedInsert(s, x); s.Push(temp); } static void Sort(Stack<int> s) { if (s.Count > 0) { int x = s.Pop(); Sort(s); SortedInsert(s, x); } } static void Main() { Stack<int> s = new Stack<int>(); s.Push(11); s.Push(2); s.Push(32); s.Push(3); s.Push(41); Sort(s); while (s.Count > 0) { Console.Write(s.Pop() + " "); } Console.WriteLine(); } } JavaScript function sortedInsert(s, x) { if (s.length === 0 || x > s[s.length - 1]) { s.push(x); return; } let temp = s.pop(); sortedInsert(s, x); s.push(temp); } function sort(s) { if (s.length > 0) { let x = s.pop(); sort(s); sortedInsert(s, x); } } let s = []; s.push(11); s.push(2); s.push(32); s.push(3); s.push(41); sort(s); let result = ''; while (s.length > 0) { result += s.pop() + ' '; } console.log(result.trim()); Output41 32 11 3 2 Time Complexity: O(n^2). Auxiliary Space: O(n) due to call stack and temporary stack.To read more about another approach Refer, Sort a stack using a temporary stack Comment More infoAdvertise with us Next Article Sort a Stack using Recursion K kartik Follow Improve Article Tags : Stack Recursion DSA Amazon Yahoo Goldman Sachs IBM Kuliza STL +5 More Practice Tags : AmazonGoldman SachsIBMKulizaYahooRecursionStackSTL +4 More Similar Reads Introduction to Recursion The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution 14 min read What is Recursion? Recursion is defined as a process which calls itself directly or indirectly and the corresponding function is called a recursive function.Example 1 : Sum of Natural Numbers Let us consider a problem to find the sum of natural numbers, there are several ways of doing that but the simplest approach is 8 min read Difference between Recursion and Iteration A program is called recursive when an entity calls itself. A program is called iterative when there is a loop (or repetition).Example: Program to find the factorial of a number C++ // C++ program to find factorial of given number #include<bits/stdc++.h> using namespace std; // ----- Recursion 6 min read Types of Recursions What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inord 15+ min read Finite and Infinite Recursion with examples The process in which a function calls itself directly or indirectly is called Recursion and the corresponding function is called a Recursive function. Using Recursion, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Tr 6 min read What is Tail Recursion Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call.For example the following function print() is tail recursive.C++// An example of tail recursive funct 7 min read What is Implicit recursion? What is Recursion? Recursion is a programming approach where a function repeats an action by calling itself, either directly or indirectly. This enables the function to continue performing the action until a particular condition is satisfied, such as when a particular value is reached or another con 5 min read Why is Tail Recursion optimization faster than normal Recursion? What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recur 4 min read Recursive Functions A Recursive function can be defined as a routine that calls itself directly or indirectly. In other words, a recursive function is a function that solves a problem by solving smaller instances of the same problem. This technique is commonly used in programming to solve problems that can be broken do 4 min read Difference Between Recursion and Induction Recursion and induction are fundamental ideas in computer science and mathematics that might be regularly used to solve problems regarding repetitive structures. Recursion is a programming technique in which a function calls itself to solve the problem, whilst induction is a mathematical proof techn 4 min read Like