If I have a sorting algorithm, and I want to sort by some field of a structure. I’m basically looking for the possibility of a parameter (sortBy in this case) being able to determine whether fieldOne would be compared, or fieldTwo–without continually checking for the correct field to use.
void func(SomeType *arr, int length, int sortBy) {
int i;
for(int i = 0; i < length, i++) {
if(sortBy == 1) {
doSomethingTo(arr[i].fieldOne);
}
else if(sortBy == 2) {
doSomethingTo(arr[i].fieldTwo);
}
// etc
}
}
You can observe what the Standard C
qsort()does. It sorts any array of any type, using a comparator function:The comparator function returns a negative value if
v1should sort beforev2, a positive value if it should sort after, and zero if the values are equal under this sorting criterion. Note that it is necessary to compare two values; it is not sufficient to compare one value with its own navel.In your example, you are sorting a fixed type, it seems. You could use
qsort(), or you can borrow the comparator type idea, and adapt it to your sort:Your comparator might be:
If you need to do more comparisons, you can add extra pairs of tests after the the
else ifclause, leaving the equality case to the end.