Counting Sort | The main function that sort the given string arr [ ] in alphabetical order ; The output character array that will have sorted arr ; Create a count array to store count of inidividul characters and initialize count array as 0 ; store count of each character ; Change count [ i ] so that count [ i ] now contains actual position of this character in output array ; Build the output character array To make it stable we are operating in reverse order . ; Copy the output array to arr , so that arr now contains sorted characters ; Driver method
function sort ( arr ) { var n = arr . length ; var output = Array . from ( { length : n } , ( _ , i ) => 0 ) ; var count = Array . from ( { length : 256 } , ( _ , i ) => 0 ) ; for ( var i = 0 ; i < n ; ++ i ) ++ count [ arr [ i ] . charCodeAt ( 0 ) ] ; for ( var i = 1 ; i <= 255 ; ++ i ) count [ i ] += count [ i - 1 ] ; for ( var i = n - 1 ; i >= 0 ; i -- ) { output [ count [ arr [ i ] . charCodeAt ( 0 ) ] - 1 ] = arr [ i ] ; -- count [ arr [ i ] . charCodeAt ( 0 ) ] ; } for ( var i = 0 ; i < n ; ++ i ) arr [ i ] = output [ i ] ; return arr ; } var arr = [ ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' ] ; arr = sort ( arr ) ; document . write ( " " ) ; for ( var i = 0 ; i < arr . length ; ++ i ) document . write ( arr [ i ] ) ; cript