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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSorted ( string s , int l ) { stack < char > Stack ; stack < char > tempstack ; Stack . push ( s [ 0 ] ) ; for ( int i = 1 ; i < l ; i ++ ) { int a = s [ i ] ; int b = Stack . top ( ) ; if ( ( a - b ) >= 1 or ( a == b ) ) Stack . push ( s [ i ] ) ; else if ( ( b - a ) >= 1 ) { while ( ( b - a ) >= 1 ) { tempstack . push ( Stack . top ( ) ) ; Stack . pop ( ) ; if ( Stack . size ( ) > 0 ) b = Stack . top ( ) ; else break ; } Stack . push ( s [ i ] ) ; while ( tempstack . size ( ) > 0 ) { Stack . push ( tempstack . top ( ) ) ; tempstack . pop ( ) ; } } } string answer ; while ( Stack . size ( ) > 0 ) { answer = Stack . top ( ) + answer ; Stack . pop ( ) ; } cout << answer << endl ; } int main ( ) { string s = " geeksforgeeks " ; int l = s . length ( ) ; printSorted ( s , l ) ; return 0 ; }