Given a stack, the task is to sort it using recursion.
Example:
Input: elements present in stack from top to bottom -3 14 18 -5 30
Output: 30 18 14 -3 -5
Explanation: The given stack is sorted know 30 > 18 > 14 > -3 > -5
Input: elements present in stack from top to bottom 1 2 3
Output: 3 2 1
Explanation: The given stack is sorted know 3 > 2 > 1
How to Sort a Stack Using Stack
The idea of the solution is to hold all values in Function Call Stack until the stack becomes empty. When the stack becomes empty, insert all held items one by one in sorted order. and then print the stack
Illustration:
Below is the illustration of above approach
- Let us illustrate sorting of stack using the above example:
First pop all the elements from the stack and store popped element in the variable ‘temp’. After popping all the elements function’s stack frame will look like this:
-3 | stack frame 1 |
14 | stack frame 2 |
18 | stack frame 3 |
-5 | stack frame 4 |
30 | stack frame 5 |
- Now stack is empty so function insert in sorted order is called and it inserts 30 (from stack frame 5) at the bottom of the stack. Now stack looks like the below:
- Now next element -5 (from stack frame 4) is picked. Since -5 < 30, -5 is inserted at the bottom of the stack. Now stack becomes:
- Next 18 (from stack frame 3) is picked. Since 18 < 30, 18 is inserted below 30. Now stack becomes:
- Next 14 (from stack frame 2) is picked. Since 14 < 30 and 14 < 18, it is inserted below 18. Now stack becomes:
- Now -3 (from stack frame 1) is picked, as -3 < 30 and -3 < 18 and -3 < 14, it is inserted below 14. Now stack becomes:
Follow the steps mentioned below to implement the idea:
- Create a stack and push all the elements in it.
- Call sortStack(), which will pop an element from the stack and pass the popped element to function sortInserted(), then it will keep calling itself until the stack is empty.
- Whenever sortInserted() is called it will insert the passed element in stack in sorted order.
- Print the stack
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
struct stack {
int data;
struct stack* next;
};
void initStack( struct stack** s) { *s = NULL; }
int isEmpty( struct stack* s)
{
if (s == NULL)
return 1;
return 0;
}
void push( struct stack** s, int x)
{
struct stack* p = ( struct stack*) malloc ( sizeof (*p));
if (p == NULL) {
fprintf (stderr, "Memory allocation failed.\n" );
return ;
}
p->data = x;
p->next = *s;
*s = p;
}
int pop( struct stack** s)
{
int x;
struct stack* temp;
x = (*s)->data;
temp = *s;
(*s) = (*s)->next;
free (temp);
return x;
}
int top( struct stack* s) { return (s->data); }
void sortedInsert( struct stack** s, int x)
{
if (isEmpty(*s) or x > top(*s)) {
push(s, x);
return ;
}
int temp = pop(s);
sortedInsert(s, x);
push(s, temp);
}
void sortStack( struct stack** s)
{
if (!isEmpty(*s)) {
int x = pop(s);
sortStack(s);
sortedInsert(s, x);
}
}
void printStack( struct stack* s)
{
while (s) {
cout << s->data << " " ;
s = s->next;
}
cout << "\n" ;
}
int main( void )
{
struct stack* top;
initStack(&top);
push(&top, 30);
push(&top, -5);
push(&top, 18);
push(&top, 14);
push(&top, -3);
cout << "Stack elements before sorting:\n" ;
printStack(top);
sortStack(&top);
cout << "\n" ;
cout << "Stack elements after sorting:\n" ;
printStack(top);
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
struct stack {
int data;
struct stack* next;
};
void initStack( struct stack** s) { *s = NULL; }
int isEmpty( struct stack* s)
{
if (s == NULL)
return 1;
return 0;
}
void push( struct stack** s, int x)
{
struct stack* p = ( struct stack*) malloc ( sizeof (*p));
if (p == NULL) {
fprintf (stderr, "Memory allocation failed.\n" );
return ;
}
p->data = x;
p->next = *s;
*s = p;
}
int pop( struct stack** s)
{
int x;
struct stack* temp;
x = (*s)->data;
temp = *s;
(*s) = (*s)->next;
free (temp);
return x;
}
int top( struct stack* s) { return (s->data); }
void sortedInsert( struct stack** s, int x)
{
if (isEmpty(*s) || x > top(*s)) {
push(s, x);
return ;
}
int temp = pop(s);
sortedInsert(s, x);
push(s, temp);
}
void sortStack( struct stack** s)
{
if (!isEmpty(*s)) {
int x = pop(s);
sortStack(s);
sortedInsert(s, x);
}
}
void printStack( struct stack* s)
{
while (s) {
printf ( "%d " , s->data);
s = s->next;
}
printf ( "\n" );
}
int main( void )
{
struct stack* top;
initStack(&top);
push(&top, 30);
push(&top, -5);
push(&top, 18);
push(&top, 14);
push(&top, -3);
printf ( "Stack elements before sorting:\n" );
printStack(top);
sortStack(&top);
printf ( "\n\n" );
printf ( "Stack elements after sorting:\n" );
printStack(top);
return 0;
}
|
Java
import java.util.ListIterator;
import java.util.Stack;
class Test {
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);
}
static void sortStack(Stack<Integer> s)
{
if (!s.isEmpty()) {
int x = s.pop();
sortStack(s);
sortedInsert(s, x);
}
}
static void printStack(Stack<Integer> s)
{
ListIterator<Integer> lt = s.listIterator();
while (lt.hasNext())
lt.next();
while (lt.hasPrevious())
System.out.print(lt.previous() + " " );
}
public static void main(String[] args)
{
Stack<Integer> s = new Stack<>();
s.push( 30 );
s.push(- 5 );
s.push( 18 );
s.push( 14 );
s.push(- 3 );
System.out.println(
"Stack elements before sorting: " );
printStack(s);
sortStack(s);
System.out.println(
" \n\nStack elements after sorting:" );
printStack(s);
}
}
|
Python3
def sortedInsert(s, element):
if len (s) = = 0 or element > s[ - 1 ]:
s.append(element)
return
else :
temp = s.pop()
sortedInsert(s, element)
s.append(temp)
def sortStack(s):
if len (s) ! = 0 :
temp = s.pop()
sortStack(s)
sortedInsert(s, temp)
def printStack(s):
for i in s[:: - 1 ]:
print (i, end = " " )
print ()
if __name__ = = '__main__' :
s = []
s.append( 30 )
s.append( - 5 )
s.append( 18 )
s.append( 14 )
s.append( - 3 )
print ( "Stack elements before sorting: " )
printStack(s)
sortStack(s)
print ( "\nStack elements after sorting: " )
printStack(s)
|
C#
using System;
using System.Collections;
public class GFG {
static void sortedInsert(Stack s, int x)
{
if (s.Count == 0 || x > ( int )s.Peek()) {
s.Push(x);
return ;
}
int temp = ( int )s.Peek();
s.Pop();
sortedInsert(s, x);
s.Push(temp);
}
static void sortStack(Stack s)
{
if (s.Count > 0) {
int x = ( int )s.Peek();
s.Pop();
sortStack(s);
sortedInsert(s, x);
}
}
static void printStack(Stack s)
{
foreach ( int c in s) { Console.Write(c + " " ); }
}
public static void Main(String[] args)
{
Stack s = new Stack();
s.Push(30);
s.Push(-5);
s.Push(18);
s.Push(14);
s.Push(-3);
Console.WriteLine(
"Stack elements before sorting: " );
printStack(s);
sortStack(s);
Console.WriteLine(
" \n\nStack elements after sorting:" );
printStack(s);
}
}
|
Javascript
<script>
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 sortStack(s)
{
if (s.length!=0)
{
let x = s.pop();
sortStack(s);
sortedInsert(s, x);
}
}
function printStack(s)
{
for (let i=s.length-1;i>=0;i--)
{
document.write(s[i]+ " " );
}
document.write( "<br>" )
}
let s=[];
s.push(30);
s.push(-5);
s.push(18);
s.push(14);
s.push(-3);
document.write(
"Stack elements before sorting: <br>" );
printStack(s);
sortStack(s);
document.write(
" <br><br>Stack elements after sorting:<br>" );
printStack(s);
</script>
|
Time Complexity: O(N2).
Auxiliary Space: O(N) use of Stack
Another Method Using STL stack, collection in Java
C++
#include <stack>
#include <iostream>
using namespace std;
void sortStack(stack< int > &s) {
if (s.empty())
return ;
int x = s.top();
s.pop();
sortStack(s);
stack< int > tempStack;
while (!s.empty() && s.top() > x) {
tempStack.push(s.top());
s.pop();
}
s.push(x);
while (!tempStack.empty()) {
s.push(tempStack.top());
tempStack.pop();
}
}
int main() {
stack< int > s;
s.push(34);
s.push(3);
s.push(31);
s.push(98);
s.push(92);
s.push(23);
sortStack(s);
cout << "Sorted numbers are: " ;
while (!s.empty()) {
cout << s.top() << " " ;
s.pop();
}
return 0;
}
|
Java
import java.util.Stack;
public class Main {
public static void sortStack(Stack<Integer> s)
{
if (s.empty())
return ;
int x = s.pop();
sortStack(s);
Stack<Integer> tempStack = new Stack<>();
while (!s.empty() && s.peek() > x) {
tempStack.push(s.pop());
}
s.push(x);
while (!tempStack.empty()) {
s.push(tempStack.pop());
}
}
public static void main(String[] args)
{
Stack<Integer> s = new Stack<>();
s.push( 34 );
s.push( 3 );
s.push( 31 );
s.push( 98 );
s.push( 92 );
s.push( 23 );
sortStack(s);
System.out.print( "Sorted numbers are: " );
while (!s.empty()) {
System.out.print(s.pop() + " " );
}
}
}
|
Python3
def sortStack(s):
if not s:
return
x = s.pop()
sortStack(s)
tempStack = []
while s and s[ - 1 ] > x:
tempStack.append(s.pop())
s.append(x)
while tempStack:
s.append(tempStack.pop())
s = []
s.append( 34 )
s.append( 3 )
s.append( 31 )
s.append( 98 )
s.append( 92 )
s.append( 23 )
sortStack(s)
print ( "Sorted numbers are: " , end = "")
while s:
print (s.pop(), end = " " )
|
C#
using System;
using System.Collections.Generic;
public class Program
{
public static void SortStack(Stack< int > s)
{
if (s.Count == 0)
return ;
int x = s.Peek();
s.Pop();
SortStack(s);
Stack< int > tempStack = new Stack< int >();
while (s.Count > 0 && s.Peek() > x) {
tempStack.Push(s.Peek());
s.Pop();
}
s.Push(x);
while (tempStack.Count > 0) {
s.Push(tempStack.Peek());
tempStack.Pop();
}
}
public static void Main()
{
Stack< int > s = new Stack< int >();
s.Push(34);
s.Push(3);
s.Push(31);
s.Push(98);
s.Push(92);
s.Push(23);
SortStack(s);
Console.Write( "Sorted numbers are: " );
while (s.Count > 0) {
Console.Write(s.Peek() + " " );
s.Pop();
}
}
}
|
Javascript
function sortStack(s) {
if (s.length <= 1) {
return ;
}
let x = s.pop();
sortStack(s);
let tempStack = [];
while (s.length !== 0 && s[s.length - 1] > x) {
tempStack.push(s.pop());
}
s.push(x);
while (tempStack.length !== 0) {
s.push(tempStack.pop());
}
}
let s = [];
s.push(34);
s.push(3);
s.push(31);
s.push(98);
s.push(92);
s.push(23);
sortStack(s);
let result = "Sorted numbers are: " ;
while (s.length !== 0) {
result += s.pop() + " " ;
}
console.log(result.trim());
|
OutputSorted numbers are: 98 92 34 31 23 3
Time complexity: O(n^2)
Auxiliary Space: O(n)