Normally sorting Array of structure objects is easy. Consider an Array of a structure (AOS)
#define ITEMS 10
typedef struct MyStruct
{
char a;
int b;
}tMyStruct;
tMyStruct arr_mystruct[ITEMS];
I first fill this array of structure with values of < a , b> pairs.
If I now want to sort this array of structures according to the integer field, I can do it using libc qsort function by using a comparison function which takes two integer arguments.
Now consider that I replace the above structure in AOS format with SOA format
#define ITEMS 10
typedef struct MyStruct
{
char a[ITEMS];
int b[ITEMS];
}tMyStruct;
tMyStruct mystruct;
Now I can still use qsort to sort the array of integers b field, however this time I need to additionally sort a (array of characters) w.r.t sorting order of b.
So my question is what is a possible efficient way to do sorting for data laid out in SOA format instead of usual AOS format?
Can anyone help me with this ? Thanks!
Probably the best way would be to use a helper array:
The
helper_cmpfunction will takehelpervalues as indices tomystruct.band compares those values:Then, after the
qsort, the helper array will contain rearranged indices ofb, telling how it should be ordered.You can use this array to both rearrange
mystruct.aandmystruct.b.Note that this is not as efficient as sorting “array of struct”. I don’t know your application, but my guess is that “struct of array”, in which the fields of the arrays are correlated is not a good idea in the first place. That is, if sorting of
baffects sorting ofa, they probably belong to the same conceptual element (call it class if you want), and it is better if they are grouped together in onestruct.