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
function printSorted ( s , l ) { var Stack = [ ] ; var tempstack = [ ] ; Stack . push ( s [ 0 ] . charCodeAt ( 0 ) ) ; for ( var i = 1 ; i < l ; i ++ ) { var a = s [ i ] . charCodeAt ( 0 ) ; var b = Stack [ Stack . length - 1 ] ; if ( ( a - b ) >= 1 || ( a == b ) ) Stack . push ( s [ i ] . charCodeAt ( 0 ) ) ; else if ( ( b - a ) >= 1 ) { while ( ( b - a ) >= 1 ) { tempstack . push ( Stack [ Stack . length - 1 ] ) ; Stack . pop ( ) ; if ( Stack . length > 0 ) b = Stack [ Stack . length - 1 ] ; else break ; } Stack . push ( s [ i ] . charCodeAt ( 0 ) ) ; while ( tempstack . length > 0 ) { Stack . push ( tempstack [ tempstack . length - 1 ] ) ; tempstack . pop ( ) ; } } } var answer = " " ; while ( Stack . length > 0 ) { answer = String . fromCharCode ( Stack [ Stack . length - 1 ] ) + answer ; Stack . pop ( ) ; } document . write ( answer ) } var s = " " ; var l = s . length ; printSorted ( s , l ) ;