Time complexity : O(N + K)
Counting sort makes assumptions about the data.
For example, it assumes that values are going to be in the range of 0 to 10 or 10 – 99.
Also, Some other assumption counting sort makes is input data will be all real numbers.
Where N is the number of elements in the input array and K is the range of input.
// C Program for counting sort
#include <stdio.h>
#include <string.h>
#define RANGE 255
// The main function that sort the given string arr[] in
// alphabetical order
void
countSort(
char
arr[])
{
// The output character array that will have sorted arr
char
output[
strlen
(arr)];
// Create a count array to store count of individual
// characters and initialize count array as 0
int
count[RANGE + 1], i;
memset
(count, 0,
sizeof
(count));
// Store count of each character
for
(i = 0; arr[i]; ++i)
++count[arr[i]];
// Change count[i] so that count[i] now contains actual
// position of this character in output array
for
(i = 1; i <= RANGE; ++i)
count[i] += count[i - 1];
// Build the output character array
for
(i = 0; arr[i]; ++i) {
output[count[arr[i]] - 1] = arr[i];
--count[arr[i]];
}
/*
For Stable algorithm
for (i = sizeof(arr)-1; i>=0; --i)
{
output[count[arr[i]]-1] = arr[i];
--count[arr[i]];
}
For Logic : See implementation
*/
// Copy the output array to arr, so that arr now
// contains sorted characters
for
(i = 0; arr[i]; ++i)
arr[i] = output[i];
}
// Driver code
int
main()
{
char
arr[] =
"geeksforgeeks"
;
//"applepp";
// Function call
countSort(arr);
printf
(
"Sorted character array is %s"
, arr);
return
0;
}