Counting sort assumes that each of the n input elements is an integer in the range 0 to k.
The basic idea of counting sort is to determine, for each input element x, the number of elements less
than x.This information can be used to place element x directly into its position in the output array.
So, I give you an example.
We assume that the input is an array A[0...n-1], we require two other arrays: the array B[0...n-1] holdsthe sorted
output, and the array C[0...k] provides temporary working storage.
#include <stdio.h> #include <malloc.h> // n is the length of A, k is the max element void counting_sort(int A[], int B[], int k, int n) { int *C, i; C = (int *)malloc(sizeof(int)*(k+1)); for (i=0; i<k+1; i++) { C[i] = 0; } // C[i]contains the number of elements equal to i for (i=0; i<n; i++) { C[A[i]]++; } // C[i] now contains the number of elements less than or equal to i for (i=1; i<n; i++) { C[i] = C[i] + C[i-1]; } //put the element A[i] to the right position for (i=n-1; i>=0; i--) { B[C[A[i]]-1] = A[i]; C[A[i]]--; } free(C); } int main() { int k, n; int A[8] = {2, 5, 3, 0, 2, 3, 0, 3}; int B[8]; n = 8; k=5; counting_sort(A, B, k, n); for (k=0; k<n; k++) { printf("%d\t", B[k]); } printf("\n"); return 0; }
And the output of B is
0 0 2 2 3 3 3 5
From "Introduction to algorithms"