Sort string of characters using Stack | Java 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
import java . io . * ; import java . util . * ; class GFG { public static void printSorted ( String s , int l ) { Stack < Character > stack = new Stack < Character > ( ) ; Stack < Character > tempstack = new Stack < Character > ( ) ; stack . push ( s . charAt ( 0 ) ) ; for ( int i = 1 ; i < l ; i ++ ) { int a = s . charAt ( i ) ; int b = ( int ) ( ( char ) stack . peek ( ) ) ; if ( ( a - b ) >= 1 || ( a == b ) ) { stack . push ( s . charAt ( i ) ) ; } else if ( ( b - a ) >= 1 ) { while ( ( b - a ) >= 1 ) { tempstack . push ( stack . peek ( ) ) ; stack . pop ( ) ; if ( stack . size ( ) > 0 ) { b = ( int ) ( ( char ) stack . peek ( ) ) ; } else { break ; } } stack . push ( s . charAt ( i ) ) ; while ( tempstack . size ( ) > 0 ) { stack . push ( tempstack . peek ( ) ) ; tempstack . pop ( ) ; } } } String answer = " " ; while ( stack . size ( ) > 0 ) { answer = stack . peek ( ) + answer ; stack . pop ( ) ; } System . out . println ( answer ) ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; int l = s . length ( ) ; printSorted ( s , l ) ; } }