Sort string of characters | JavaScript program to sort a string of characters ; 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 will do str [ i ] - ' a ' . ; Traverse the hash array and print characters ; Driver program to test above function
let MAX_CHAR = 26 ; function sortString ( str ) { let letters = new Array ( MAX_CHAR ) ; for ( let i = 0 ; i < MAX_CHAR ; i ++ ) { letters [ i ] = 0 ; } for ( let x = 0 ; x < str . length ; x ++ ) { letters [ str [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } for ( let i = 0 ; i < MAX_CHAR ; i ++ ) { for ( let j = 0 ; j < letters [ i ] ; j ++ ) { document . write ( String . fromCharCode ( i + ' ' . charCodeAt ( 0 ) ) ) ; } } } sortString ( " " ) ;