Skip to content

Commit 3aa0bb5

Browse files
committed
adding more sorts
1 parent 83e8816 commit 3aa0bb5

File tree

5 files changed

+96
-3
lines changed

5 files changed

+96
-3
lines changed

.vscode/settings.json

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"files.associations": {
3+
"*.embeddedhtml": "html",
4+
"stdlib.h": "c"
5+
}
6+
}

README.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ This is a collection of sorting algorithms implemented in C.
99
- Selection Sort
1010
- Merge Sort
1111
- Quick Sort
12+
- Counting Sort
13+
- Radix Sort
14+
- Bucket Sort
1215

1316
Other algorithms are not still implemented:
1417

1518
- Heap Sort
16-
- Counting Sort
17-
- Radix Sort
18-
- Bucket Sort
1919
- Shell Sort
2020
- Comb Sort
2121
- Gnome Sort

a.exe

-514 Bytes
Binary file not shown.

bucket_sort.c

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
void bucket_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+
12+
int buckets[max + 1];
13+
for (int i = 0; i < max + 1; i++) {
14+
buckets[i] = 0;
15+
}
16+
17+
for (int i = 0; i < n; i++) {
18+
buckets[arr[i]]++;
19+
}
20+
21+
int index = 0;
22+
for (int i = 0; i < max + 1; i++) {
23+
while (buckets[i] > 0) {
24+
arr[index++] = i;
25+
buckets[i]--;
26+
}
27+
}
28+
}
29+
30+
int main(int argc, char** argv) {
31+
int arr[] = { 5, 4, 3, 2, 1 };
32+
int n = sizeof(arr) / sizeof(arr[0]);
33+
34+
bucket_sort(arr, n);
35+
36+
for (int i = 0; i < n; i++) {
37+
printf("%d ", arr[i]);
38+
}
39+
40+
return 0;
41+
}

radix_sort.c

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
void radix_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+
12+
for (int exp = 1; max / exp > 0; exp *= 10) {
13+
int output[n];
14+
int count[10] = { 0 };
15+
16+
for (int i = 0; i < n; i++) {
17+
count[(arr[i] / exp) % 10]++;
18+
}
19+
20+
for (int i = 1; i < 10; i++) {
21+
count[i] += count[i - 1];
22+
}
23+
24+
for (int i = n - 1; i >= 0; i--) {
25+
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
26+
count[(arr[i] / exp) % 10]--;
27+
}
28+
29+
for (int i = 0; i < n; i++) {
30+
arr[i] = output[i];
31+
}
32+
}
33+
}
34+
35+
int main(int argc, char** argv) {
36+
int arr[] = { 5, 4, 3, 2, 1 };
37+
int n = sizeof(arr) / sizeof(arr[0]);
38+
39+
radix_sort(arr, n);
40+
41+
for (int i = 0; i < n; i++) {
42+
printf("%d ", arr[i]);
43+
}
44+
45+
return 0;
46+
}

0 commit comments

Comments
 (0)