Sort the Queue using Recursion | C ++ implementation of the approach ; Function to push element in last by popping from front until size becomes 0 ; Base condition ; pop front element and push this last in a queue ; Recursive call for pushing element ; Function to push an element in the queue while maintaining the sorted order ; Base condition ; If current element is less than the element at the front ; Call stack with front of queue ; Recursive call for inserting a front element of the queue to the last ; Push front element into last in a queue ; Recursive call for pushing element in a queue ; Function to sort the given queue using recursion ; Return if queue is empty ; Get the front element which will be stored in this variable throughout the recursion stack ; Remove the front element ; Recursive call ; Push the current element into the queue according to the sorting order ; Driver code ; Push elements to the queue ; Sort the queue ; Print the elements of the queue after sorting
#include <bits/stdc++.h> NEW_LINE 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 ( ) ; } }