Skip to content

Commit 04429e1

Browse files
author
Raghuveer Devulapalli
committed
Add exmaple.c
1 parent 360952b commit 04429e1

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

example.c

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#include <stdio.h>
2+
#include <stdint.h>
3+
#include <stdlib.h>
4+
#include <stdbool.h>
5+
6+
// declare function here, linker will find this when linked to
7+
// libx86simdsortcpp.so
8+
void keyvalue_qsort_float_sizet(float*, size_t*, size_t);
9+
void keyvalue_qsort_float_uint32(float*, uint32_t*, uint32_t);
10+
11+
// struct definition, we will sort an array of these:
12+
struct Point {
13+
int x;
14+
int y;
15+
float distance;
16+
};
17+
18+
#define SWAP(a, b, type) {type temp = a; a = b; b = temp;}
19+
20+
// Function to sort an array of objects:
21+
void object_qsort(struct Point* arr, size_t size)
22+
{
23+
/* (1) Create and initialize arrays of key and value */
24+
float* key = malloc(size * sizeof(float));
25+
size_t* arg = malloc(size * sizeof(size_t));
26+
bool* done = malloc(size * sizeof(bool));
27+
for (size_t ii = 0; ii < size; ++ii) {
28+
key[ii] = arr[ii].distance;
29+
arg[ii] = ii;
30+
done[ii] = false;
31+
}
32+
33+
/* (2) IndexSort using the keyvalue_qsort */
34+
keyvalue_qsort_float_sizet(key, arg, size);
35+
36+
/* (3) Permute obj array in-place */
37+
for (size_t ii = 0; ii < size; ++ii) {
38+
if (done[ii]) { continue; }
39+
done[ii] = true;
40+
size_t prev_j = ii;
41+
size_t jj = arg[ii];
42+
while (ii != jj) {
43+
SWAP(arr[prev_j], arr[jj], struct Point);
44+
done[jj] = true;
45+
prev_j = jj;
46+
jj = arg[jj];
47+
}
48+
}
49+
free(key);
50+
free(arg);
51+
free(done);
52+
}
53+
54+
int main() {
55+
const size_t size = 10;
56+
struct Point arr[size];
57+
58+
// Initialize:
59+
for (size_t ii = 0; ii < size; ++ii) {
60+
arr[ii].distance = (float) rand() / RAND_MAX;
61+
}
62+
63+
// sort:
64+
object_qsort(arr, size);
65+
66+
// check if it is sorted:
67+
printf("arr = ");
68+
for (size_t ii = 0; ii < size; ++ii) {
69+
printf("%f, ", arr[ii].distance);
70+
}
71+
printf("\n");
72+
return 0;
73+
}

0 commit comments

Comments
 (0)