Sort the Queue using Recursion | Program to print the given pattern ; 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
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 ( ) ; } } }