Program to sort string in descending order | Java program to sort a string of characters in descending order ; function to print string in sorted order ; Hash array to keep count of characters . Initially count of all charters is initialized to zero . ; Traverse string and increment count of characters ' a ' - ' a ' will be 0 , ' b ' - ' a ' will be 1 , ; so for location of character in count array we wil do str [ i ] - ' a ' . ; Traverse the hash array and print characters ; Driver code
class GFG { static int MAX_CHAR = 26 ; static void sortString ( String str ) { int charCount [ ] = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { charCount [ str . charAt ( i ) - ' a ' ] ++ ; } for ( int i = MAX_CHAR - 1 ; i >= 0 ; i -- ) { for ( int j = 0 ; j < charCount [ i ] ; j ++ ) { System . out . print ( ( char ) ( ' a ' + i ) ) ; } } } public static void main ( String [ ] args ) { String s = " alkasingh " ; sortString ( s ) ; } }