-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcounting_sort_8s.c
57 lines (45 loc) · 1.21 KB
/
counting_sort_8s.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
50
51
52
53
54
55
56
57
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
static void counting_sort_8s(uint8_t *arr, uint8_t *aux, size_t n)
{
size_t cnt[256] = { 0 };
size_t i;
// Count number of occurrences of each octet.
for (i = 0 ; i < n ; ++i) {
cnt[arr[i]]++;
}
// Calculate prefix sums.
size_t a = 0;
for (int j = 0 ; j < 256 ; ++j) {
size_t b = cnt[j];
cnt[j] = a;
a += b;
}
// Sort elements
for (i = 0 ; i < n ; ++i) {
// Get the key for the current entry.
uint8_t k = arr[i];
// Find the location this entry goes into in the output array.
size_t dst = cnt[k];
// Copy the current entry into the right place.
aux[dst] = arr[i];
// Make it so that the next 'k' will be written after this one.
// Since we process source entries in increasing order, this makes us a stable sort.
cnt[k]++;
}
}
static void print_array_8(const uint8_t *arr, size_t n) {
for (size_t i = 0 ; i < n ; ++i) {
printf("%08zx: %d\n", i, arr[i]);
}
}
int main(int argc, char *argv[]) {
uint8_t arr[] = { 255, 45, 45, 45, 1, 2, 3, 255 };
size_t N = sizeof(arr)/sizeof(arr[0]);
uint8_t *aux = malloc(sizeof(arr[0]) * N);
counting_sort_8s(arr, aux, N);
print_array_8(aux, N);
free(aux);
return EXIT_SUCCESS;
}