-
Notifications
You must be signed in to change notification settings - Fork 0
/
radixsort.c
65 lines (58 loc) · 1.39 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
#include <stdio.h>
#include <stdlib.h>
union Int32
{
int x;
unsigned char bytes[4];
};
union Int32 *count_sort(union Int32 *arr, int n, int byte);
union Int32 *radix_sort(union Int32 *arr, int n);
int main()
{
int n;
scanf("%d", &n);
union Int32 *arr = (union Int32 *) malloc(n * sizeof(union Int32));
for (int i = 0; i < n; i++)
scanf("%d", &arr[i].x);
arr = radix_sort(arr, n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i].x);
free(arr);
return (0);
}
union Int32 *radix_sort(union Int32 *arr, int n)
{
int byte = 0;
while (byte < 4)
arr = count_sort(arr, n, byte++);
return (arr);
}
union Int32 *count_sort(union Int32 *arr, int n, int byte)
{
int count[256] = {0};
union Int32 *dest = (union Int32 *) malloc(n * sizeof(union Int32));
for (int i = 0; i < n; i++)
{
if (byte != 3)
count[arr[i].bytes[byte]]++;
else
count[arr[i].bytes[byte] ^ 128]++;
}
for (int i = 255; i >= 0; i--)
{
count[i] = 0;
for (int j = 0; j < i; j++)
count[i] += count[j];
}
for (int i = 0; i < n; i++)
{
int j;
if (byte < 3)
j = count[arr[i].bytes[byte]]++;
else
j =count[arr[i].bytes[byte] ^ 128]++;
dest[j] = arr[i];
}
free(arr);
return (dest);
}