Skip to content

Commit 83e8816

Browse files
committed
add counting_sort
1 parent 741f707 commit 83e8816

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

Diff for: a.exe

3 Bytes
Binary file not shown.

Diff for: counting_sort.c

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
void counting_sort(int *arr, int n) {
5+
int max = arr[0];
6+
for (int i = 1; i < n; i++) {
7+
if (arr[i] > max) {
8+
max = arr[i];
9+
}
10+
}
11+
int *count = (int *)malloc(sizeof(int) * (max + 1));
12+
for (int i = 0; i <= max; i++) {
13+
count[i] = 0;
14+
}
15+
for (int i = 0; i < n; i++) {
16+
count[arr[i]]++;
17+
}
18+
int j = 0;
19+
for (int i = 0; i <= max; i++) {
20+
while (count[i] > 0) {
21+
arr[j++] = i;
22+
count[i]--;
23+
}
24+
}
25+
free(count);
26+
}
27+
28+
int main(int argc, char** argv) {
29+
int arr[] = { 5, 4, 3, 2, 1 };
30+
int n = sizeof(arr) / sizeof(arr[0]);
31+
32+
counting_sort(arr, n);
33+
34+
for (int i = 0; i < n; i++) {
35+
printf("%d ", arr[i]);
36+
}
37+
38+
return 0;
39+
}

0 commit comments

Comments
 (0)