TheAlgorithms-C/sorting/counting_Sort.c

50 lines
1.0 KiB
C
Raw Normal View History

/*
> 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>
#include <string.h>
#include <stdlib.h>
2019-11-09 21:04:40 +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);
int *a = (int *)malloc(n * sizeof(int));
2019-11-09 21:04:40 +03:00
printf("Enter %d elements in array :\n", n);
for (i = 0; i < n; i++)
2019-11-09 21:04:40 +03:00
{
scanf("%d", &a[i]);
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]));
for (i = 0; i < n; i++)
2019-11-09 21:04:40 +03:00
b[a[i]]++; //hashing number to array index
for (i = 0; i < (l + 1); i++) //unstable , stabilized by prefix sum array
2019-11-09 21:04:40 +03:00
{
if (b[i] > 0)
2019-11-09 21:04:40 +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]--;
}
}
}
free(a);
2020-04-24 03:53:53 +03:00
free(b);
2019-11-09 21:04:40 +03:00
return 0;
}