To sort the array, use qsort() and pass the comparison function.
Here is one that gives the correct result for all possible values of the price member:
typedef struct profile { char gender[1]; double soc; int price; ... } PROFILE; int compare_price(const void *a, const void *b) { const PROFILE *oa = a; const PROFILE *ob = b; return (oa->price > ob->price) - (oa->price < ob->price); } int compare_soc(const void *a, const void *b) { const PROFILE *oa = a; const PROFILE *ob = b; return (oa->soc > ob->soc) - (oa->soc < ob->soc); }
Notes:
simply subtracting the values produces incorrect results if the difference is not int . For example, -2 and INT_MAX cannot be correctly compared with the subtraction method. It will not work for floating point values either.
the above method can be used for all comparable types, including double , with the exception of NaN .
If you want to process NaN , here's how to group them at the end:
#include <math.h> int compare_soc_nan_at_the_end(const void *a, const void *b) { const PROFILE *oa = a; const PROFILE *ob = b; if (isnan(oa->soc)) { return isnan(ob->soc) ? 0 : 1; } else if (isnan(ob->soc)) { return -1; } else { return (oa->soc > ob->soc) - (oa->soc < ob->soc); } }
source share