Sort string of characters using Stack | C # program to sort string of characters using stack ; Function to print the characters in sorted order ; Primary stack ; Secondary stack ; Append first character ; Iterate for all character in string ; i - th character ASCII ; stack 's top element ASCII  ; If greater or equal to top element then push to stack ; If smaller , then push all element to the temporary stack ; Push all greater elements ; Push operation ; Push till the stack is not - empty ; Push the i - th character ; Push the tempstack back to stack ; Print the stack in reverse order ; Driver Code
using System ; using System . Collections ; class GFG { static void printSorted ( string s , int l ) { Stack stack = new Stack ( ) ; Stack tempstack = new Stack ( ) ; stack . Push ( s [ 0 ] ) ; for ( int i = 1 ; i < l ; i ++ ) { int a = s [ i ] ; int b = ( int ) ( ( char ) stack . Peek ( ) ) ; if ( ( a - b ) >= 1 || ( a == b ) ) stack . Push ( s [ i ] ) ; else if ( ( b - a ) >= 1 ) { while ( ( b - a ) >= 1 ) { tempstack . Push ( stack . Peek ( ) ) ; stack . Pop ( ) ; if ( stack . Count > 0 ) b = ( int ) ( ( char ) stack . Peek ( ) ) ; else break ; } stack . Push ( s [ i ] ) ; while ( tempstack . Count > 0 ) { stack . Push ( tempstack . Peek ( ) ) ; tempstack . Pop ( ) ; } } } string answer = " " ; while ( stack . Count > 0 ) { answer = stack . Peek ( ) + answer ; stack . Pop ( ) ; } Console . WriteLine ( answer ) ; } static void Main ( ) { string s = " geeksforgeeks " ; int l = s . Length ; printSorted ( s , l ) ; } }