Umm, I think I'd better show you several patterns of compare_function to use with qsort() library function. Then you yourself will be able to pick what you actually need.
1. Just beginning from the scratch, suppose you want to sort
in ascending order.
Your compare function will be like this -
Code: Select all
int comp_func(const int *x,const int *y)
{
return (*x - *y);
}
2. Proceed on to sort
in descending order, you'll write -
Code: Select all
int comp_func(const char *x,const char *y)
{
return (strcmp(y,x));
}
3. Now, consider this structure -
Code: Select all
struct data_
{
int a,
double b;
};
If you need to sort
such that it will be sorted in ascending order of a, & ties will be broken in descending order of b, your compare function will be something like this -
Code: Select all
int comp_func(const data_ *x,const data_ *y)
{
if(x->a==y->a)
{
if(x->b > y->b)
return -1;
else if(x->b < y->b)
return 1;
else
return 0;
}
else if(x->a > y->a)
return 1;
else
return -1;
}
You should never take more than you give in the circle of life.