Skip to content

Commit 275752f

Browse files
counting sort in c
1 parent 91826a7 commit 275752f

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

c-cpp/14_sorts/counting_sort.c

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <stdbool.h>
4+
#include <string.h>
5+
6+
void dump(int *arr, int size)
7+
{
8+
int i;
9+
10+
for (i = 0; i < size; i++)
11+
printf("%08d\n", arr[i]);
12+
}
13+
14+
// content in arr must be positive integer
15+
void counting_sort(int *arr, int size)
16+
{
17+
int max, i;
18+
int *count, *tmp;
19+
20+
if (size <= 1)
21+
return;
22+
23+
max = 0;
24+
// find the biggest integer
25+
for (i = 0; i < size; i++) {
26+
if (max < arr[i])
27+
max = arr[i];
28+
}
29+
30+
// init count to 0
31+
count = (int*)malloc((max+1) * sizeof(int));
32+
tmp = (int*)malloc(size * sizeof(int));
33+
if (!count || !tmp)
34+
return;
35+
memset(count, 0, (max + 1) * sizeof(int));
36+
37+
// counting
38+
for (i = 0; i < size; i++)
39+
count[arr[i]]++;
40+
for (i = 1; i < max + 1; i++)
41+
count[i] = count[i-1] + count[i];
42+
43+
// iterate arr and put it to the correct index in tmp
44+
for (i = 0; i < size; i++){
45+
int index = count[arr[i]] - 1;
46+
tmp[index] = arr[i];
47+
count[arr[i]]--;
48+
}
49+
50+
// move back to arr
51+
memcpy(arr, tmp, size * sizeof(int));
52+
}
53+
54+
void counting_sort_test()
55+
{
56+
int test_data[10] = {3, 23, 98, 1, 27, 36, 52, 89, 76, 44};
57+
58+
counting_sort(test_data, 10);
59+
dump(test_data, 10);
60+
}
61+
62+
int main()
63+
{
64+
counting_sort_test();
65+
return 0;
66+
}

0 commit comments

Comments
 (0)