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
def printSorted ( s , l ) : NEW_LINE INDENT stack = [ ] NEW_LINE tempstack = [ ] NEW_LINE stack . append ( s [ 0 ] ) NEW_LINE for i in range ( 1 , l ) : NEW_LINE INDENT a = ord ( s [ i ] ) NEW_LINE b = ord ( stack [ - 1 ] ) NEW_LINE if ( ( a - b ) >= 1 or ( a == b ) ) : NEW_LINE INDENT stack . append ( s [ i ] ) NEW_LINE DEDENT elif ( ( b - a ) >= 1 ) : NEW_LINE INDENT while ( ( b - a ) >= 1 ) : NEW_LINE INDENT tempstack . append ( stack . pop ( ) ) NEW_LINE if ( len ( stack ) > 0 ) : NEW_LINE INDENT b = ord ( stack [ - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT stack . append ( s [ i ] ) NEW_LINE while ( len ( tempstack ) > 0 ) : NEW_LINE INDENT stack . append ( tempstack . pop ( ) ) NEW_LINE DEDENT DEDENT DEDENT print ( ' ' . join ( stack ) ) NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE l = len ( s ) NEW_LINE printSorted ( s , l ) NEW_LINE