Q:

How to sort an array of structures according to values of one of its members, breaking ties on the basis of another member?

Suppose there is a structure:
struct x
{

int a,b,c;

};

The array of structure contains arr[0]={4,2,5}, arr[1]={6,3,1}, arr[2]={4,1,8}
then how can we sort this array in ascending order depending on value of member 'a',.
tie will be broken according to value of member 'b'.
So array after sorting should be : arr[2],then arr[0], then arr[1].
I have used qsort(arr,n,sizeof(struct x),compare);
with compare function defined as
int compare(const void* a, const void * b)
{

return (*(int*)a-*(int*)b);

}

What modification I hav to do if I have to break ties acccording to member b.(currently it is breaking ties on first come first serve basis).

A:

int compare(const void* a, const void * b){
    struct x x = *(struct x*)a;
    struct x y = *(struct x*)b;

    return x.a < y.a ? -1 : (x.a > y.a ? 1 : (x.b < y.b ? -1 : x.b > y.b));
}

