Example 1 — Count then rebuild
Keys are in the range 0 to 9.
#include <stdio.h>
int main(void) {
int a[] = {4, 2, 2, 8, 3, 3, 1};
int n = 7, count[10] = {0};
for (int i = 0; i < n; i++) count[a[i]]++;
printf("counts:");
for (int v = 0; v < 10; v++)
if (count[v]) printf(" %d->%d", v, count[v]);
int k = 0;
for (int v = 0; v < 10; v++)
for (int c = count[v]; c > 0; c--) a[k++] = v;
printf("\nsorted:");
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
return 0;
} How It Works
- The count array records how many times each value appears.
- Writing each value
count[v]times rebuilds the array in order. - No two elements are ever compared.
