-
Notifications
You must be signed in to change notification settings - Fork 59
/
example.c
87 lines (77 loc) · 2.27 KB
/
example.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
76
77
78
79
80
81
82
83
84
85
86
87
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
// declare function here, linker will find this when linked to
// libx86simdsortcpp.so
void keyvalue_qsort_float_sizet(float *, size_t *, size_t);
void keyvalue_qsort_float_uint32(float *, uint32_t *, uint32_t);
void keyvalue_qsort_sizet_sizet(size_t *, size_t *, size_t);
void keyvalue_qsort_sizet_uint32(size_t *, uint32_t *, uint32_t);
void keyvalue_qsort_uint32_sizet(uint32_t *, size_t *, size_t);
void keyvalue_qsort_uint32_uint32(uint32_t *, uint32_t *, uint32_t);
void keyvalue_qsort_int32_sizet(int32_t *, size_t *, size_t);
void keyvalue_qsort_int32_uint32(int32_t *, uint32_t *, uint32_t);
// struct definition, we will sort an array of these:
struct Point {
int x;
int y;
float distance;
size_t metric;
};
#define SWAP(a, b, type) \
{ \
type temp = a; \
a = b; \
b = temp; \
}
// Function to sort an array of objects:
void object_qsort(struct Point *arr, size_t size)
{
/* (1) Create and initialize arrays of key and value */
size_t *key = malloc(size * sizeof(size_t));
size_t *arg = malloc(size * sizeof(size_t));
bool *done = malloc(size * sizeof(bool));
for (size_t ii = 0; ii < size; ++ii) {
key[ii] = arr[ii].metric;
arg[ii] = ii;
done[ii] = false;
}
/* (2) IndexSort using the keyvalue_qsort */
keyvalue_qsort_sizet_sizet(key, arg, size);
/* (3) Permute obj array in-place */
for (size_t ii = 0; ii < size; ++ii) {
if (done[ii]) { continue; }
done[ii] = true;
size_t prev_j = ii;
size_t jj = arg[ii];
while (ii != jj) {
SWAP(arr[prev_j], arr[jj], struct Point);
done[jj] = true;
prev_j = jj;
jj = arg[jj];
}
}
free(key);
free(arg);
free(done);
}
int main()
{
const size_t size = 10;
struct Point arr[size];
// Initialize:
for (size_t ii = 0; ii < size; ++ii) {
arr[ii].distance = (float)rand() / RAND_MAX;
arr[ii].metric = rand() % 100;
}
// sort:
object_qsort(arr, size);
// check if it is sorted:
printf("arr = ");
for (size_t ii = 0; ii < size; ++ii) {
printf("%ld, ", arr[ii].metric);
}
printf("\n");
return 0;
}