Open In App

Sort a stack using a temporary stack

Last Updated : 25 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a stack of integers, sort it in ascending order using another temporary stack.

Examples: 

Input : [34, 3, 31, 98, 92, 23]
Output : [3, 23, 31, 34, 92, 98]

Input : [3, 5, 1, 4, 2, 8]
Output : [1, 2, 3, 4, 5, 8] 
Recommended Practice

Algorithm:

  1. Create a temporary stack say tmpStack.
  2. While input stack is NOT empty do this: 
    • Pop an element from input stack call it temp
    • while temporary stack is NOT empty and top of temporary stack is greater than temp, 
      pop from temporary stack and push it to the input stack
    • push temp in temporary stack
  3. The sorted numbers are in tmpStack

Here is a dry run of the above pseudo code.  

input: [34, 3, 31, 98, 92, 23]

Element taken out: 23
input: [34, 3, 31, 98, 92]
tmpStack: [23]

Element taken out: 92
input: [34, 3, 31, 98]
tmpStack: [23, 92]

Element taken out: 98
input: [34, 3, 31]
tmpStack: [23, 92, 98]

Element taken out: 31
input: [34, 3, 98, 92]
tmpStack: [23, 31]

Element taken out: 92
input: [34, 3, 98]
tmpStack: [23, 31, 92]

Element taken out: 98
input: [34, 3]
tmpStack: [23, 31, 92, 98]

Element taken out: 3
input: [34, 98, 92, 31, 23]
tmpStack: [3]

Element taken out: 23
input: [34, 98, 92, 31]
tmpStack: [3, 23]

Element taken out: 31
input: [34, 98, 92]
tmpStack: [3, 23, 31]

Element taken out: 92
input: [34, 98]
tmpStack: [3, 23, 31, 92]

Element taken out: 98
input: [34]
tmpStack: [3, 23, 31, 92, 98]

Element taken out: 34
input: [98, 92]
tmpStack: [3, 23, 31, 34]

Element taken out: 92
input: [98]
tmpStack: [3, 23, 31, 34, 92]

Element taken out: 98
input: []
tmpStack: [3, 23, 31, 34, 92, 98]

final sorted list: [3, 23, 31, 34, 92, 98]

Implementation:

C++




// C++ program to sort a stack using an
// auxiliary stack.
#include <bits/stdc++.h>
using namespace std;
 
// This function return the sorted stack
stack<int> sortStack(stack<int> &input)
{
    stack<int> tmpStack;
 
    while (!input.empty())
    {
        // pop out the first element
        int tmp = input.top();
        input.pop();
 
        // while temporary stack is not empty and top
        // of stack is lesser than temp
        while (!tmpStack.empty() && tmpStack.top() < tmp)
        {
            // pop from temporary stack and push
            // it to the input stack
            input.push(tmpStack.top());
            tmpStack.pop();
        }
 
        // push temp in temporary of stack
        tmpStack.push(tmp);
    }
 
    return tmpStack;
}
 
// main function
int main()
{
    stack<int> input;
    input.push(34);
    input.push(3);
    input.push(31);
    input.push(98);
    input.push(92);
    input.push(23);
 
    // This is the temporary stack
    stack<int> tmpStack = sortStack(input);
    cout << "Sorted numbers are:\n";
 
    while (!tmpStack.empty())
    {
        cout << tmpStack.top()<< " ";
        tmpStack.pop();
    }
}


Java




// Java program to sort a stack using
// a auxiliary stack.
import java.util.*;
 
class SortStack
{
    // This function return the sorted stack
    public static Stack<Integer> sortstack(Stack<Integer>
                                             input)
    {
        Stack<Integer> tmpStack = new Stack<Integer>();
        while(!input.isEmpty())
        {
            // pop out the first element
            int tmp = input.pop();
         
            // while temporary stack is not empty and
            // top of stack is lesser than temp
            while(!tmpStack.isEmpty() && tmpStack.peek()
                                                 < tmp)
            {
                // pop from temporary stack and
                // push it to the input stack
            input.push(tmpStack.pop());
            }
             
            // push temp in temporary of stack
            tmpStack.push(tmp);
        }
        return tmpStack;
    }
     
    // Driver Code
    public static void main(String args[])
    {
        Stack<Integer> input = new Stack<Integer>();
        input.add(34);
        input.add(3);
        input.add(31);
        input.add(98);
        input.add(92);
        input.add(23);
     
        // This is the temporary stack
        Stack<Integer> tmpStack=sortstack(input);
        System.out.println("Sorted numbers are:");
     
        while (!tmpStack.empty())
        {
            System.out.print(tmpStack.pop()+" ");
        }
    }
}
// This code is contributed by Danish Kaleem


Python3




# Python program to sort a
# stack using auxiliary stack.
 
# This function return the sorted stack
def sortStack ( stack ):
    tmpStack = createStack()
    while(isEmpty(stack) == False):
         
        # pop out the first element
        tmp = top(stack)
        pop(stack)
 
        # while temporary stack is not
        # empty and top of stack is
        # lesser than temp
        while(isEmpty(tmpStack) == False and
             int(top(tmpStack)) < int(tmp)):
             
            # pop from temporary stack and
            # push it to the input stack
            push(stack,top(tmpStack))
            pop(tmpStack)
 
        # push temp in temporary of stack
        push(tmpStack,tmp)
     
    return tmpStack
 
# Below is a complete running
# program for testing above
# function.
 
# Function to create a stack.
# It initializes size of stack
# as 0
def createStack():
    stack = []
    return stack
 
# Function to check if
# the stack is empty
def isEmpty( stack ):
    return len(stack) == 0
 
# Function to push an
# item to stack
def push( stack, item ):
    stack.append( item )
 
# Function to get top
# item of stack
def top( stack ):
    p = len(stack)
    return stack[p-1]
 
# Function to pop an
# item from stack
def pop( stack ):
 
    # If stack is empty
    # then error
    if(isEmpty( stack )):
        print("Stack Underflow ")
        exit(1)
 
    return stack.pop()
 
# Function to print the stack
def prints(stack):
    for i in range(len(stack)-1, -1, -1):
        print(stack[i], end = ' ')
    print()
 
# Driver Code
stack = createStack()
push( stack, str(34) )
push( stack, str(3) )
push( stack, str(31) )
push( stack, str(98) )
push( stack, str(92) )
push( stack, str(23) )
 
print("Sorted numbers are: ")
sortedst = sortStack ( stack )
prints(sortedst)
 
# This code is contributed by
# Prasad Kshirsagar


C#




// C# program to sort a stack using
// a auxiliary stack.
using System;
using System.Collections.Generic;
 
class GFG
{
// This function return the sorted stack
public static Stack<int> sortstack(Stack<int> input)
{
    Stack<int> tmpStack = new Stack<int>();
    while (input.Count > 0)
    {
        // pop out the first element
        int tmp = input.Pop();
 
        // while temporary stack is not empty and
        // top of stack is lesser than temp
        while (tmpStack.Count > 0 && tmpStack.Peek() < tmp)
        {
            // pop from temporary stack and
            // push it to the input stack
            input.Push(tmpStack.Pop());
        }
 
        // push temp in temporary of stack
        tmpStack.Push(tmp);
    }
    return tmpStack;
}
 
// Driver Code
public static void Main(string[] args)
{
    Stack<int> input = new Stack<int>();
    input.Push(34);
    input.Push(3);
    input.Push(31);
    input.Push(98);
    input.Push(92);
    input.Push(23);
 
    // This is the temporary stack
    Stack<int> tmpStack = sortstack(input);
    Console.WriteLine("Sorted numbers are:");
 
    while (tmpStack.Count > 0)
    {
        Console.Write(tmpStack.Pop() + " ");
    }
}
}
 
// This code is contributed by Shrikant13


Javascript




<script>
    // Javascript program to sort a stack using
    // a auxiliary stack.
     
    // This function return the sorted stack
    function sortstack(input)
    {
        let tmpStack = [];
        while (input.length > 0)
        {
            // pop out the first element
            let tmp = input.pop();
 
            // while temporary stack is not empty and
            // top of stack is lesser than temp
            while (tmpStack.length > 0 && tmpStack[tmpStack.length - 1] < tmp)
            {
                // pop from temporary stack and
                // push it to the input stack
                input.push(tmpStack[tmpStack.length - 1]);
                tmpStack.pop()
            }
 
            // push temp in temporary of stack
            tmpStack.push(tmp);
        }
        return tmpStack;
    }
     
    let input = [];
    input.push(34);
    input.push(3);
    input.push(31);
    input.push(98);
    input.push(92);
    input.push(23);
   
    // This is the temporary stack
    let tmpStack = sortstack(input);
    document.write("Sorted numbers are:" + "</br>");
   
    while (tmpStack.length > 0)
    {
        document.write(tmpStack[tmpStack.length - 1] + " ");
        tmpStack.pop();
    }
     
    // This code is contributed by rameshtravel07.
</script>


Output

Sorted numbers are:
3 23 31 34 92 98 

Time Complexity: O(n2) where n is the total number of integers in the given stack.
Auxiliary Space: O(n)

Microsoft

 



Previous Article
Next Article

Similar Reads

Swap three variables without using temporary variable
Given three variables, a, b and c, swap them without temporary variable.Example : Input : a = 10, b = 20 and c = 30 Output : a = 30, b = 10 and c = 20 Method 1 (Using Arithmetic Operators) The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum. We have already discussed swappin
12 min read
Reverse string without using any temporary variable
We are given a string. We are also given indexes of first and last characters in string. The task is to reverse the string without using any extra variable. Examples: Input : str = "abc" Output : str = "cba" Input : str = "GeeksforGeeks" Output : str = "skeeGrofskeeG" If we take a look at program to reverse a string or array, all we need to do is s
4 min read
How to swap two numbers without using a temporary variable?
Given two variables, x, and y, swap two variables without using a third variable. Method 1 (Using Addition and subtraction) The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum. C/C++ Code // C++ Program to swap two numbers without // using temporary variable #include
15+ min read
Javascript program to swap two numbers without using temporary variable
To swap two numbers without using a temporary variable, we have multiple approaches. In this article, we are going to learn how to swap two numbers without using a temporary variable. Below are the approaches used to swap two numbers without using a temporary variable: Table of Content Using Arithmetic OperatorsUsing Bitwise XORA mixture of bitwise
6 min read
Swapping four variables without temporary variable
Suppose we have four variables a, b, c, d and we want to perform swapping of these variables in the following manner a = b, b = c, c = d, d = a without using any other fifth or temporary variable Solution : Step 1. Swap a and b without using any other variable a = a + b b = a - b a = a - b Step 2. Swap b and c without using any other variable b = b
7 min read
Comparison among Bubble Sort, Selection Sort and Insertion Sort
Bubble Sort, Selection Sort, and Insertion Sort are simple sorting algorithms that are commonly used to sort small datasets or as building blocks for more complex sorting algorithms. Here's a comparison of the three algorithms: Bubble Sort:Time complexity: O(n^2) in the worst and average cases, O(n) in the best case (when the input array is already
15 min read
Tag sort or Bucket sort or Bin sort in Python
Tag sort, also known as Bucket sort or Bin sort, is a non-comparison based sorting algorithm that distributes elements of an array into a number of "buckets", and then sorts each bucket individually. Tag sort or Bucket sort or Bin sort Algorithm:Determine Range:Find the maximum and minimum values in the input array to determine the range of tags ne
2 min read
Sort an array using Bubble Sort without using loops
Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops. Examples: Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5 Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4 Approach: The idea to implement Bubble Sort without using loops is based on the following observations: The sorting algorith
9 min read
Sort an array of pairs using Java Arrays.sort() with custom Comparator
Given an array of pairs of integers. The task is to sort the array with respect to the second element of the pair. Examples: Input: [(1, 2), (3, 5), (2, 6), (1, 7)]Output: [(1, 2), (3, 5), (2, 6), (1, 7)] Input: [(10, 20), (20, 30), (5, 6), (2, 5)]Output: [(2, 5), (5, 6), (10, 20), (20, 30)] Approach: Store the pairs in an array using a user-define
2 min read
Sort an Array which contain 1 to N values in O(N) using Cycle Sort
Prerequisite: Cycle SortGiven an array arr[] of elements from 1 to N, the task is to sort the given array in O(N) time.Examples: Input: arr[] = { 2, 1, 5, 4, 3} Output: 1 2 3 4 5 Explanation: Since arr[0] = 2 is not at correct position, then swap arr[0] with arr[arr[0] - 1] Now array becomes: arr[] = {1, 2, 5, 4, 3}Now arr[2] = 5 is not at correct
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg