forked from TheAlgorithms/C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
counting_sort.c
49 lines (41 loc) · 1.04 KB
/
counting_sort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
> 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
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i, n, l = 0;
printf("Enter size of array = ");
scanf("%d", &n);
int *a = (int *)malloc(n * sizeof(int));
printf("Enter %d elements in array :\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
if (a[i] > l)
l = a[i];
}
int *b = (int *)malloc((l + 1) * sizeof(int));
memset(b, 0, (l + 1) * sizeof(b[0]));
for (i = 0; i < n; i++)
b[a[i]]++; // hashing number to array index
for (i = 0; i < (l + 1); i++) // unstable , stabilized by prefix sum array
{
if (b[i] > 0)
{
while (b[i] != 0) // for case when number exists more than once
{
printf("%d ", i);
b[i]--;
}
}
}
free(a);
free(b);
return 0;
}