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 ; Copy the output array to arr , so that arr now contains sorted characters ; Driver program to test above function
def countSort ( arr ) : NEW_LINE INDENT output = [ 0 for i in range ( len ( arr ) ) ] NEW_LINE count = [ 0 for i in range ( 256 ) ] NEW_LINE for i in arr : NEW_LINE INDENT count [ ord ( i ) ] += 1 NEW_LINE DEDENT for i in range ( 256 ) : NEW_LINE INDENT count [ i ] += count [ i - 1 ] NEW_LINE DEDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT output [ count [ ord ( arr [ i ] ) ] - 1 ] = arr [ i ] NEW_LINE count [ ord ( arr [ i ] ) ] -= 1 NEW_LINE DEDENT ans = [ " " for _ in arr ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT ans [ i ] = output [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = " geeksforgeeks " NEW_LINE ans = countSort ( arr ) NEW_LINE print ( " Sorted ▁ character ▁ array ▁ is ▁ % ▁ s " % ( " " . join ( ans ) ) ) NEW_LINE