2019-11-07 16:09:38 +03:00
|
|
|
/*
|
|
|
|
> Counting sort is a sorting technique based on keys between a specific range.
|
|
|
|
> integer sorting algorithm
|
|
|
|
> Worst-case performance O(n+k)
|
|
|
|
> Stabilized by prefix sum array
|
|
|
|
*/
|
2019-11-09 21:04:40 +03:00
|
|
|
|
|
|
|
#include <stdio.h>
|
2020-04-24 03:45:45 +03:00
|
|
|
#include <stdlib.h>
|
2020-05-29 23:23:24 +03:00
|
|
|
#include <string.h>
|
2019-11-09 21:04:40 +03:00
|
|
|
|
2019-11-07 16:09:38 +03:00
|
|
|
int main()
|
|
|
|
{
|
2019-11-09 21:04:40 +03:00
|
|
|
int i, n, l = 0;
|
|
|
|
|
|
|
|
printf("Enter size of array = ");
|
|
|
|
scanf("%d", &n);
|
|
|
|
|
2020-04-24 03:45:45 +03:00
|
|
|
int *a = (int *)malloc(n * sizeof(int));
|
2019-11-09 21:04:40 +03:00
|
|
|
printf("Enter %d elements in array :\n", n);
|
2020-04-24 03:45:45 +03:00
|
|
|
for (i = 0; i < n; i++)
|
2019-11-09 21:04:40 +03:00
|
|
|
{
|
|
|
|
scanf("%d", &a[i]);
|
2020-04-24 03:45:45 +03:00
|
|
|
if (a[i] > l)
|
2019-11-09 21:04:40 +03:00
|
|
|
l = a[i];
|
|
|
|
}
|
|
|
|
|
2020-04-24 03:53:53 +03:00
|
|
|
int *b = (int *)malloc((l + 1) * sizeof(int));
|
2019-11-09 21:04:40 +03:00
|
|
|
memset(b, 0, (l + 1) * sizeof(b[0]));
|
|
|
|
|
2020-06-28 18:25:37 +03:00
|
|
|
for (i = 0; i < n; i++) b[a[i]]++; // hashing number to array index
|
2019-11-09 21:04:40 +03:00
|
|
|
|
2020-06-28 18:25:37 +03:00
|
|
|
for (i = 0; i < (l + 1); i++) // unstable , stabilized by prefix sum array
|
2019-11-09 21:04:40 +03:00
|
|
|
{
|
2020-04-24 03:45:45 +03:00
|
|
|
if (b[i] > 0)
|
2019-11-09 21:04:40 +03:00
|
|
|
{
|
2020-06-28 18:25:37 +03:00
|
|
|
while (b[i] != 0) // for case when number exists more than once
|
2019-11-09 21:04:40 +03:00
|
|
|
{
|
|
|
|
printf("%d ", i);
|
|
|
|
b[i]--;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-24 03:45:45 +03:00
|
|
|
free(a);
|
2020-04-24 03:53:53 +03:00
|
|
|
free(b);
|
2019-11-09 21:04:40 +03:00
|
|
|
return 0;
|
|
|
|
}
|