Counting sort is another sorting technique using keys in the specific number of the range. It works with the objects having distinct key & values. Counting sort uses array indexes to sort the given string based on the keys and values. In this tutorial, I am going to share a c program for counting sort with example.
This program will sort the given string arr[] in the alphabatical order. Copy the below code and execute it with the help of c compiler and see the output. At the end of this tutorial, we have shared the real-time program output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include <stdio.h> #include <string.h> #define RANGE 255 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[] = "freewebmentor"; countSort(arr); printf("Sorted character array is %sn", arr); return 0; } |
Sorted character array is beeeefmnorrtwn
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.