Try this compare function
int compare(const void *a, const void *b)
{
const struct data_t *m = a;
const struct data_t *n = b;
if(m->x != n->x)
return (m->x > n->x) - (m->x < n->x);
if(m->y != n->y)
return m->y - n->y;
if(m->z != n->z)
return (m->z > n->z) - (m->z < n->z);
if(m->k != n->k)
return (m->k > n->k) - (m->x < n->k);
return 0;
}
This will compare the first column x. If x is the same in the two elements, it moves to the second column y. If the second column is the same, it moves to the third column and so on.
We want the difference between the two values. Example, m->y - n->y. The compare function should return an integer value 0, negative, or positive.
When comparing double values, we cannot use m->x - n->x, because the return value for compare is int. We use a comparison function instead.
Testing
struct data_t
{
double x;
int y;
double z;
double k;
};
int compare(const void *a, const void *b)
{
const struct data_t *m = a;
const struct data_t *n = b;
if(m->x != n->x)
return (m->x > n->x) ? 1 : -1;
if(m->y != n->y)
return m->y - n->y;
if(m->z != n->z)
return (m->z > n->z) ? 1 : -1;
if(m->k != n->k)
return (m->k > n->k) ? 1 : -1;
return 0;
}
int main(void)
{
struct data_t data[] =
{
{ 0.060493, 3, 0.4, 7 },//1st column is the same
{ 0.060493, 2, 0.5, 8 },
{ 0.060493, 1, 0.6, 9 },
{ 0.060493, 3, 0.3, 4 },//1st & 2nd columns are the same
{ 0.060493, 3, 0.2, 5 },
{ 0.060493, 3, 0.1, 6 },
{ 0.060493, 1, 0.5, 3 },//1st & 2nd & 3rd columns are the same
{ 0.060493, 1, 0.5, 2 },
{ 0.060493, 1, 0.5, 1 },
{ 0.122609, 0, 0.8, 9 },
{ 0.125379, 1, 0.2, 3 },
{ 0.131486, 1, 0.3, 3 },
};
int count = sizeof(data) / sizeof(data[0]);
qsort(data, count, sizeof(data[0]), compare);
for(int i = 0; i < count; i++)
{
printf("%.6f %d %.1f %.0f\n",
data[i].x, data[i].y, data[i].z, data[i].k);
}
return 0;
}
output:
0.060493 1 0.5 1
0.060493 1 0.5 2
0.060493 1 0.5 3
0.060493 1 0.6 9
0.060493 2 0.5 8
0.060493 3 0.1 6
0.060493 3 0.2 5
0.060493 3 0.3 4
0.060493 3 0.4 7
0.122609 0 0.8 9
0.125379 1 0.2 3
0.131486 1 0.3 3
comparefunction is bizarre. Please look up some examples of, presumably,qsort, and be wary of testing floating point values for equality. Please post the Minimal, Complete, and Verifiable example that shows the problem.return m->k > n->k;andreturn m->x > n->x;are useless, they will never be reached, you can only return 1 object from a function. And I highly recommend adding some brackets{ ... }to yourifstatement to make it clear with you want, or at least changing the indentation. What you have now is misleading.