-
Notifications
You must be signed in to change notification settings - Fork 0
/
RadixSort.c
76 lines (51 loc) · 1.47 KB
/
RadixSort.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#ifndef RADIX
#define RADIX
#include "arvores.h"
#include <assert.h>
#include <errno.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#define DECIMAL 10
#define DIGIT(n, p) (n / p) % DECIMAL
static int GetMax(const T *array, const size_t size) {
int max = array[0].codigo;
for (size_t index = 0; index < size; ++index) {
if (max < array[index].codigo) {
max = array[index].codigo;
}
}
return max;
}
static int CountingSort(T *array, const size_t size, int exponent) {
unsigned counting[DECIMAL];
T *buffer = (T *)malloc(size * sizeof(T));
if (buffer == NULL) {
return ENOMEM;
}
memset(counting, 0, DECIMAL * sizeof(int));
for (size_t index = 0; index < size; ++index) {
++counting[DIGIT(array[index].codigo, exponent)];
}
unsigned accumulation = 0;
for (size_t index = 0; index < DECIMAL; ++index) {
unsigned count = counting[index];
counting[index] = accumulation;
accumulation += count;
}
for (size_t index = 0; index < size; ++index) {
buffer[counting[DIGIT(array[index].codigo, exponent)]++] = array[index];
}
memcpy(array, buffer, size * sizeof(T));
free(buffer);
exponent *= DECIMAL;
return EXIT_SUCCESS;
}
int RadixSortLSD(T *array, const size_t size) {
int max = GetMax(array, size);
for (int exponent = 1; (max / exponent) > 0; exponent *= DECIMAL) {
assert(CountingSort(array, size, exponent) == EXIT_SUCCESS);
}
return EXIT_SUCCESS;
}
#endif /* ifndef RADIX */