-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcsort.c
73 lines (57 loc) · 1.32 KB
/
csort.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
/* assert */
#include <assert.h>
/* EXIT_SUCCESS, rand */
#include <stdlib.h>
/* strtol */
#include <stdio.h>
static int
csort(unsigned const k,
unsigned const n,
unsigned const * const in,
unsigned * const out)
{
unsigned * const count = calloc(k + 1, sizeof(*count));
if (NULL == count) {
return -1;
}
for (unsigned i = 0; i < n; i++) {
count[in[i]]++;
}
unsigned total = 0;
for (unsigned i = 0; i <= k; i++) {
unsigned const counti = count[i];
count[i] = total;
total += counti;
}
for (unsigned i = 0; i < n; i++) {
out[count[in[i]]] = in[i];
count[in[i]]++;
}
free(count);
return 0;
}
int
main(int argc, char *argv[]) {
/* Get array size from command line */
unsigned n = strtol(argv[1], NULL, 10);
/* Get key size from command line */
unsigned k = strtol(argv[2], NULL, 10);
/* Allocate memory */
unsigned * const a = malloc(n * sizeof(*a));
unsigned * const b = malloc(n * sizeof(*b));
/* Populate with random values */
for (unsigned i = 0; i < n; i++) {
a[i] = rand() % (1u << k);
}
/* Sort array */
int const ret = csort(1u << k, n, a, b);
assert(0 == ret);
/* Validate sorted array */
for (unsigned i = 1; i < n; i++) {
assert(b[i] >= b[i - 1]);
}
/* Free memory */
free(a);
free(b);
return EXIT_SUCCESS;
}