Program to sort string in descending order | Javascript 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
let MAX_CHAR = 26 ; function sortString ( str ) { let charCount = new Array ( MAX_CHAR ) ; for ( let i = 0 ; i < charCount . length ; i ++ ) { charCount [ i ] = 0 ; } for ( let i = 0 ; i < str . length ; i ++ ) { charCount [ str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } for ( let i = MAX_CHAR - 1 ; i >= 0 ; i -- ) { for ( let j = 0 ; j < charCount [ i ] ; j ++ ) { document . write ( String . fromCharCode ( ' ' . charCodeAt ( 0 ) + i ) ) ; } } } let s = " " ; sortString ( s ) ;