Sort the Queue using Recursion

09 Nov, 2021
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 20Input: 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 then 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 then all elements of the queue then push your element into the queue.
If the item (returned by function call stack) is greater then 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 then all elements of the queue then push your element into the queue.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to push element in last by// popping from front until size becomes 0void FrontToLast(queue<int>& q, int qsize){    // Base condition    if (qsize <= 0)        return;     // pop front element and push    // this last in a queue    q.push(q.front());    q.pop();     // Recursive call for pushing element    FrontToLast(q, qsize - 1);} // Function to push an element in the queue// while maintaining the sorted ordervoid pushInQueue(queue<int>& q, int temp, int qsize){     // Base condition    if (q.empty() || qsize == 0) {        q.push(temp);        return;    }     // If current element is less than    // the element at the front    else if (temp <= q.front()) {         // Call stack with front of queue        q.push(temp);         // Recursive call for inserting a front        // element of the queue to the last        FrontToLast(q, qsize);    }    else {         // Push front element into        // last in a queue        q.push(q.front());        q.pop();         // Recursive call for pushing        // element in a queue        pushInQueue(q, temp, qsize - 1);    }} // Function to sort the given// queue using recursionvoid sortQueue(queue<int>& q){     // Return if queue is empty    if (q.empty())        return;     // Get the front element which will    // be stored in this variable    // throughout the recursion stack    int temp = q.front();     // Remove the front element    q.pop();     // Recursive call    sortQueue(q);     // Push the current element into the queue    // according to the sorting order    pushInQueue(q, temp, q.size());} // Driver codeint main(){     // Push elements to the queue    queue<int> qu;    qu.push(10);    qu.push(7);    qu.push(16);    qu.push(9);    qu.push(20);    qu.push(5);     // Sort the queue    sortQueue(qu);     // Print the elements of the    // queue after sorting    while (!qu.empty()) {        cout << qu.front() << " ";        qu.pop();    }}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to push element in last by// popping from front until size becomes 0static void FrontToLast(Queue<Integer> q,                        int qsize){    // Base condition    if (qsize <= 0)        return;     // pop front element and push    // this last in a queue    q.add(q.peek());    q.remove();     // Recursive call for pushing element    FrontToLast(q, qsize - 1);} // Function to push an element in the queue// while maintaining the sorted orderstatic void pushInQueue(Queue<Integer> q,                        int temp, int qsize){     // Base condition    if (q.isEmpty() || qsize == 0)    {        q.add(temp);        return;    }     // If current element is less than    // the element at the front    else if (temp <= q.peek())    {         // Call stack with front of queue        q.add(temp);         // Recursive call for inserting a front        // element of the queue to the last        FrontToLast(q, qsize);    }    else    {         // Push front element into        // last in a queue        q.add(q.peek());        q.remove();         // Recursive call for pushing        // element in a queue        pushInQueue(q, temp, qsize - 1);    }} // Function to sort the given// queue using recursionstatic void sortQueue(Queue<Integer> q){     // Return if queue is empty    if (q.isEmpty())        return;     // Get the front element which will    // be stored in this variable    // throughout the recursion stack    int temp = q.peek();     // Remove the front element    q.remove();     // Recursive call    sortQueue(q);     // Push the current element into the queue    // according to the sorting order    pushInQueue(q, temp, q.size());} // Driver codepublic static void main(String[] args){         // Push elements to the queue    Queue<Integer> qu = new LinkedList<>();    qu.add(10);    qu.add(7);    qu.add(16);    qu.add(9);    qu.add(20);    qu.add(5);     // Sort the queue    sortQueue(qu);     // Print the elements of the    // queue after sorting    while (!qu.isEmpty())    {        System.out.print(qu.peek() + " ");        qu.remove();    }}} // This code is contributed by PrinciRaj1992
# defining a class Queueclass 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)) # Function to push element in last by# popping from front until size becomes 0def FrontToLast(q, qsize) :     # Base condition    if qsize <= 0:        return     # pop front element and push    # this last in a queue    q.put(q.get())     # Recursive call for pushing element    FrontToLast(q, qsize - 1) # Function to push an element in the queue# while maintaining the sorted orderdef pushInQueue(q, temp, qsize) :         # Base condition    if q.empty() or qsize == 0:        q.put(temp)        return         # If current element is less than    # the element at the front    elif temp <= q.front() :         # Call stack with front of queue        q.put(temp)         # Recursive call for inserting a front        # element of the queue to the last        FrontToLast(q, qsize)     else :         # Push front element into        # last in a queue        q.put(q.get())         # Recursive call for pushing        # element in a queue        pushInQueue(q, temp, qsize - 1)     # Function to sort the given# queue using recursiondef sortQueue(q):         # Return if queue is empty    if q.empty():        return     # Get the front element which will    # be stored in this variable    # throughout the recursion stack    temp = q.get()         # Recursive call    sortQueue(q)     # Push the current element into the queue    # according to the sorting order    pushInQueue(q, temp, q.size()) # Driver codequ = Queue() # Data is inserted into Queue# using put() Data is inserted# at the endqu.put(10)qu.put(7)qu.put(16)qu.put(9)qu.put(20)qu.put(5) # Sort the queuesortQueue(qu) # Print the elements of the# queue after sortingwhile not qu.empty():    print(qu.get(), end = ' ')         # This code is contributed by Sadik Ali
// Program to print the given patternusing System;using System.Collections.Generic; class GFG{ // Function to push element in last by// popping from front until size becomes 0static void FrontToLast(Queue<int> q,                        int qsize){    // Base condition    if (qsize <= 0)        return;     // pop front element and push    // this last in a queue    q.Enqueue(q.Peek());    q.Dequeue();     // Recursive call for pushing element    FrontToLast(q, qsize - 1);} // Function to push an element in the queue// while maintaining the sorted orderstatic void pushInQueue(Queue<int> q,                        int temp, int qsize){     // Base condition    if (q.Count == 0 || qsize == 0)    {        q.Enqueue(temp);        return;    }     // If current element is less than    // the element at the front    else if (temp <= q.Peek())    {         // Call stack with front of queue        q.Enqueue(temp);         // Recursive call for inserting a front        // element of the queue to the last        FrontToLast(q, qsize);    }    else    {         // Push front element into        // last in a queue        q.Enqueue(q.Peek());        q.Dequeue();         // Recursive call for pushing        // element in a queue        pushInQueue(q, temp, qsize - 1);    }} // Function to sort the given// queue using recursionstatic void sortQueue(Queue<int> q){     // Return if queue is empty    if (q.Count==0)        return;     // Get the front element which will    // be stored in this variable    // throughout the recursion stack    int temp = q.Peek();     // Remove the front element    q.Dequeue();     // Recursive call    sortQueue(q);     // Push the current element into the queue    // according to the sorting order    pushInQueue(q, temp, q.Count);} // Driver codepublic static void Main(String[] args){         // Push elements to the queue    Queue<int> qu = new Queue<int>();    qu.Enqueue(10);    qu.Enqueue(7);    qu.Enqueue(16);    qu.Enqueue(9);    qu.Enqueue(20);    qu.Enqueue(5);     // Sort the queue    sortQueue(qu);     // Print the elements of the    // queue after sorting    while (qu.Count != 0)    {        Console.Write(qu.Peek() + " ");        qu.Dequeue();    }}} // This code is contributed by Princi Singh
<script>    // Javascript implementation of the approach         // Function to push element in last by    // popping from front until size becomes 0    function FrontToLast(q, qsize)    {        // Base condition        if (qsize <= 0)            return;         // pop front element and push        // this last in a queue        q.push(q[0]);        q.shift();         // Recursive call for pushing element        FrontToLast(q, qsize - 1);    }     // Function to push an element in the queue    // while maintaining the sorted order    function pushInQueue(q, temp, qsize)    {         // Base condition        if (q.length == 0 || qsize == 0)        {            q.push(temp);            return;        }         // If current element is less than        // the element at the front        else if (temp <= q[0])        {             // Call stack with front of queue            q.push(temp);             // Recursive call for inserting a front            // element of the queue to the last            FrontToLast(q, qsize);        }        else        {             // Push front element into            // last in a queue            q.push(q[0]);            q.shift();             // Recursive call for pushing            // element in a queue            pushInQueue(q, temp, qsize - 1);        }    }     // Function to sort the given    // queue using recursion    function sortQueue(q)    {         // Return if queue is empty        if (q.length==0)            return;         // Get the front element which will        // be stored in this variable        // throughout the recursion stack        let temp = q[0];         // Remove the front element        q.shift();         // Recursive call        sortQueue(q);         // Push the current element into the queue        // according to the sorting order        pushInQueue(q, temp, q.length);    }         // Push elements to the queue    let qu = [];    qu.push(10);    qu.push(7);    qu.push(16);    qu.push(9);    qu.push(20);    qu.push(5);       // Sort the queue    sortQueue(qu);       // Print the elements of the    // queue after sorting    while (qu.length != 0)    {        document.write(qu[0] + " ");        qu.shift();    } // This code is contributed by mukesh07.</script>
5 7 9 10 16 20
 
princiraj1992
princi singh
chsadik99
nidhi_biet
mukesh07
Constructive Algorithms
Queue
Recursion
Sorting
Recursion
Sorting
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Priority Queue | Introduction to Priority Queue
Sliding Window Maximum (Maximum of all subarrays of size k)
What is Data Structure: Types, Classifications and Applications
LRU Cache Implementation
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction