Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Sort a Stack using Recursion
Next article icon

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 > 1

Input: [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 top
  • Else 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()); 

Output
41 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


Next Article
Sort a Stack using Recursion

K

kartik
Improve
Article Tags :
  • Stack
  • Recursion
  • DSA
  • Amazon
  • Yahoo
  • Goldman Sachs
  • IBM
  • Kuliza
  • STL
Practice Tags :
  • Amazon
  • Goldman Sachs
  • IBM
  • Kuliza
  • Yahoo
  • Recursion
  • Stack
  • STL

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences