Sort the Queue using Recursion | defining a class Queue ; 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 ; Recursive call ; Push the current element into the queue according to the sorting order ; Driver code ; Data is inserted into Queue using put ( ) Data is inserted at the end ; Sort the queue ; Print the elements of the queue after sorting
class Queue : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . queue = [ ] NEW_LINE DEDENT def put ( self , item ) : NEW_LINE INDENT self . queue . append ( item ) NEW_LINE DEDENT def get ( self ) : NEW_LINE INDENT if len ( self . queue ) < 1 : NEW_LINE INDENT return None NEW_LINE DEDENT return self . queue . pop ( 0 ) NEW_LINE DEDENT def front ( self ) : NEW_LINE INDENT return self . queue [ 0 ] NEW_LINE DEDENT def size ( self ) : NEW_LINE INDENT return len ( self . queue ) NEW_LINE DEDENT def empty ( self ) : NEW_LINE INDENT return not ( len ( self . queue ) ) NEW_LINE DEDENT DEDENT def FrontToLast ( q , qsize ) : NEW_LINE INDENT if qsize <= 0 : NEW_LINE INDENT return NEW_LINE DEDENT q . put ( q . get ( ) ) NEW_LINE FrontToLast ( q , qsize - 1 ) NEW_LINE DEDENT def pushInQueue ( q , temp , qsize ) : NEW_LINE INDENT if q . empty ( ) or qsize == 0 : NEW_LINE INDENT q . put ( temp ) NEW_LINE return NEW_LINE DEDENT elif temp <= q . front ( ) : NEW_LINE INDENT q . put ( temp ) NEW_LINE FrontToLast ( q , qsize ) NEW_LINE DEDENT else : NEW_LINE INDENT q . put ( q . get ( ) ) NEW_LINE pushInQueue ( q , temp , qsize - 1 ) NEW_LINE DEDENT DEDENT def sortQueue ( q ) : NEW_LINE INDENT if q . empty ( ) : NEW_LINE INDENT return NEW_LINE DEDENT temp = q . get ( ) NEW_LINE sortQueue ( q ) NEW_LINE pushInQueue ( q , temp , q . size ( ) ) NEW_LINE DEDENT qu = Queue ( ) NEW_LINE qu . put ( 10 ) NEW_LINE qu . put ( 7 ) NEW_LINE qu . put ( 16 ) NEW_LINE qu . put ( 9 ) NEW_LINE qu . put ( 20 ) NEW_LINE qu . put ( 5 ) NEW_LINE sortQueue ( qu ) NEW_LINE while not qu . empty ( ) : NEW_LINE INDENT print ( qu . get ( ) , end = ' ▁ ' ) NEW_LINE DEDENT