A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/dsa/sort-a-stack-using-recursion/ below:

Sort a Stack using Recursion

Sort a Stack using Recursion

Last Updated : 23 Jul, 2025

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.

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());

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


Sort a stack using recursion


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4