Sorting a Queue without extra space | C # program to implement sorting a queue data structure ; Queue elements after sorted Index are already sorted . This function returns index of minimum element from front to sortedIndex ; This is dequeue ( ) in C ++ STL ; we add the condition i <= sortedIndex because we don 't want to traverse  on the sorted part of the   queue, which is the right part. ; This is enqueue ( ) in C ++ STL ; Moves given minimum element to rear of queue ; SortQueue Function ; Driver Code ; Sort queue ; Print sorted queue
using System ; using System . Collections . Generic ; class GFG { static int minIndex ( ref Queue < int > q , int sortedIndex ) { int min_index = - 1 ; int min_val = int . MaxValue ; int n = q . Count ; for ( int i = 0 ; i < n ; i ++ ) { int curr = q . Peek ( ) ; q . Dequeue ( ) ; if ( curr <= min_val && i <= sortedIndex ) { min_index = i ; min_val = curr ; } q . Enqueue ( curr ) ; } return min_index ; } static void insertMinToRear ( ref Queue < int > q , int min_index ) { int min_val = 0 ; int n = q . Count ; for ( int i = 0 ; i < n ; i ++ ) { int curr = q . Peek ( ) ; q . Dequeue ( ) ; if ( i != min_index ) q . Enqueue ( curr ) ; else min_val = curr ; } q . Enqueue ( min_val ) ; } static void sortQueue ( ref Queue < int > q ) { for ( int i = 1 ; i <= q . Count ; i ++ ) { int min_index = minIndex ( ref q , q . Count - i ) ; insertMinToRear ( ref q , min_index ) ; } } static void Main ( ) { Queue < int > q = new Queue < int > ( ) ; q . Enqueue ( 30 ) ; q . Enqueue ( 11 ) ; q . Enqueue ( 15 ) ; q . Enqueue ( 4 ) ; sortQueue ( ref q ) ; while ( q . Count != 0 ) { Console . Write ( q . Peek ( ) + " ▁ " ) ; q . Dequeue ( ) ; } Console . WriteLine ( ) ; } }