Sort the Queue using Recursion
Last Updated :
05 Jan, 2023
Given a queue and the task is to sort it using recursion without using any loop. We can only use the following functions of queue:
empty(q): Tests whether the queue is empty or not.
push(q): Adds a new element to the queue.
pop(q): Removes front element from the queue.
size(q): Returns the number of elements in a queue.
front(q): Returns the value of the front element without removing it.
Examples:
Input: queue = {10, 7, 16, 9, 20, 5}
Output: 5 7 9 10 16 20
Input: queue = {0, -2, -1, 2, 3, 1}
Output: -2 -1 0 1 2 3
Approach: The idea of the solution is to hold all values in the function call stack until the queue becomes empty. When the queue becomes empty, insert all held items one by one in sorted order. Here sorted order is important.
How to manage sorted order?
Whenever you get the item from the function call stack, then first calculate the size of the queue and compare it with the elements of queue. Here, two cases arises:
- If the item (returned by function call stack) is greater than the front element of the queue then dequeue front element and enqueue this element into the same queue by decreasing the size.
- If the item is less than the front element from the queue then enqueue the element in the queue and dequeue the remaining element from the queue and enqueue by decreasing size repeat the case 1 and 2 unless size becomes zero. Take care of one thing, if size became zero and your element remains greater than all elements of the queue then push your element into the queue.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void FrontToLast(queue< int >& q, int qsize)
{
if (qsize <= 0)
return ;
q.push(q.front());
q.pop();
FrontToLast(q, qsize - 1);
}
void pushInQueue(queue< int >& q, int temp, int qsize)
{
if (q.empty() || qsize == 0) {
q.push(temp);
return ;
}
else if (temp <= q.front()) {
q.push(temp);
FrontToLast(q, qsize);
}
else {
q.push(q.front());
q.pop();
pushInQueue(q, temp, qsize - 1);
}
}
void sortQueue(queue< int >& q)
{
if (q.empty())
return ;
int temp = q.front();
q.pop();
sortQueue(q);
pushInQueue(q, temp, q.size());
}
int main()
{
queue< int > qu;
qu.push(10);
qu.push(7);
qu.push(16);
qu.push(9);
qu.push(20);
qu.push(5);
sortQueue(qu);
while (!qu.empty()) {
cout << qu.front() << " " ;
qu.pop();
}
}
|
Java
import java.util.*;
class GFG
{
static void FrontToLast(Queue<Integer> q,
int qsize)
{
if (qsize <= 0 )
return ;
q.add(q.peek());
q.remove();
FrontToLast(q, qsize - 1 );
}
static void pushInQueue(Queue<Integer> q,
int temp, int qsize)
{
if (q.isEmpty() || qsize == 0 )
{
q.add(temp);
return ;
}
else if (temp <= q.peek())
{
q.add(temp);
FrontToLast(q, qsize);
}
else
{
q.add(q.peek());
q.remove();
pushInQueue(q, temp, qsize - 1 );
}
}
static void sortQueue(Queue<Integer> q)
{
if (q.isEmpty())
return ;
int temp = q.peek();
q.remove();
sortQueue(q);
pushInQueue(q, temp, q.size());
}
public static void main(String[] args)
{
Queue<Integer> qu = new LinkedList<>();
qu.add( 10 );
qu.add( 7 );
qu.add( 16 );
qu.add( 9 );
qu.add( 20 );
qu.add( 5 );
sortQueue(qu);
while (!qu.isEmpty())
{
System.out.print(qu.peek() + " " );
qu.remove();
}
}
}
|
Python3
class Queue:
def __init__( self ):
self .queue = []
def put( self , item):
self .queue.append(item)
def get( self ):
if len ( self .queue) < 1 :
return None
return self .queue.pop( 0 )
def front( self ):
return self .queue[ 0 ]
def size( self ):
return len ( self .queue)
def empty( self ):
return not ( len ( self .queue))
def FrontToLast(q, qsize) :
if qsize < = 0 :
return
q.put(q.get())
FrontToLast(q, qsize - 1 )
def pushInQueue(q, temp, qsize) :
if q.empty() or qsize = = 0 :
q.put(temp)
return
elif temp < = q.front() :
q.put(temp)
FrontToLast(q, qsize)
else :
q.put(q.get())
pushInQueue(q, temp, qsize - 1 )
def sortQueue(q):
if q.empty():
return
temp = q.get()
sortQueue(q)
pushInQueue(q, temp, q.size())
qu = Queue()
qu.put( 10 )
qu.put( 7 )
qu.put( 16 )
qu.put( 9 )
qu.put( 20 )
qu.put( 5 )
sortQueue(qu)
while not qu.empty():
print (qu.get(), end = ' ' )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void FrontToLast(Queue< int > q,
int qsize)
{
if (qsize <= 0)
return ;
q.Enqueue(q.Peek());
q.Dequeue();
FrontToLast(q, qsize - 1);
}
static void pushInQueue(Queue< int > q,
int temp, int qsize)
{
if (q.Count == 0 || qsize == 0)
{
q.Enqueue(temp);
return ;
}
else if (temp <= q.Peek())
{
q.Enqueue(temp);
FrontToLast(q, qsize);
}
else
{
q.Enqueue(q.Peek());
q.Dequeue();
pushInQueue(q, temp, qsize - 1);
}
}
static void sortQueue(Queue< int > q)
{
if (q.Count==0)
return ;
int temp = q.Peek();
q.Dequeue();
sortQueue(q);
pushInQueue(q, temp, q.Count);
}
public static void Main(String[] args)
{
Queue< int > qu = new Queue< int >();
qu.Enqueue(10);
qu.Enqueue(7);
qu.Enqueue(16);
qu.Enqueue(9);
qu.Enqueue(20);
qu.Enqueue(5);
sortQueue(qu);
while (qu.Count != 0)
{
Console.Write(qu.Peek() + " " );
qu.Dequeue();
}
}
}
|
Javascript
<script>
function FrontToLast(q, qsize)
{
if (qsize <= 0)
return ;
q.push(q[0]);
q.shift();
FrontToLast(q, qsize - 1);
}
function pushInQueue(q, temp, qsize)
{
if (q.length == 0 || qsize == 0)
{
q.push(temp);
return ;
}
else if (temp <= q[0])
{
q.push(temp);
FrontToLast(q, qsize);
}
else
{
q.push(q[0]);
q.shift();
pushInQueue(q, temp, qsize - 1);
}
}
function sortQueue(q)
{
if (q.length==0)
return ;
let temp = q[0];
q.shift();
sortQueue(q);
pushInQueue(q, temp, q.length);
}
let qu = [];
qu.push(10);
qu.push(7);
qu.push(16);
qu.push(9);
qu.push(20);
qu.push(5);
sortQueue(qu);
while (qu.length != 0)
{
document.write(qu[0] + " " );
qu.shift();
}
</script>
|
Time Complexity: The time complexity of this code is O(n^2), as the time taken to sort the queue is O(n^2) due to the use of recursion. The function pushInQueue() is called n times, and each time it calls the function FrontToLast() which takes O(n) time, resulting in a time complexity of O(n^2).
Auxiliary Space: The Auxiliary Space of this code is O(n), as the maximum size of the queue will be n, where n is the number of elements in the queue.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...