text: Counting Sort | C ++ Program for 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 individual 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 code
code: #include <bits/stdc++.h> NEW_LINE #include <string.h> NEW_LINE using namespace std ; #define RANGE  255 NEW_LINE void countSort ( char arr [ ] ) { char output [ strlen ( arr ) ] ; int count [ RANGE + 1 ] , i ; memset ( count , 0 , sizeof ( count ) ) ; for ( i = 0 ; arr [ i ] ; ++ i ) ++ count [ arr [ i ] ] ; for ( i = 1 ; i <= RANGE ; ++ i ) count [ i ] += count [ i - 1 ] ; for ( i = 0 ; arr [ i ] ; ++ i ) { output [ count [ arr [ i ] ] - 1 ] = arr [ i ] ; -- count [ arr [ i ] ] ; } for ( i = 0 ; arr [ i ] ; ++ i ) arr [ i ] = output [ i ] ; } int main ( ) { char arr [ ] = " geeksforgeeks " ; countSort ( arr ) ; cout << " Sorted ▁ character ▁ array ▁ is ▁ " << arr ; return 0 ; }