Search code examples
cqsort

qsort on struct with number and char, sort on number first and then sort on alphabet with same number


Would like to qsort on struct with number and char, sort on number first and then sort on alphabet with same number Here is the struct i have

typedef struct{
    char word[101];
    int freq;
}WordArray;

Here is the logic I followed: Sort on freq first ()

int cmpffunc (const void * a, const void * b)
{
    WordArray *WordArrayA = (WordArray *)a;
    WordArray *WordArrayB = (WordArray *)b;
    return ( WordArrayB->freq - WordArrayA->freq );
}
qsort(array, arrayLength, sizeof(WordArray), cmpffunc);

Which works fine, then I tried to sort on the alphabet with same freq number. Here is the thing I tried but non of them work as expected:

int cmpwfunc (const void * a, const void * b)
{
    WordArray *A = (WordArray *)a;
    WordArray *B = (WordArray *)b;
    if (A->freq == B->freq){
        return strcmp(A->word,B->word);
    }
    else{
        return -1;
    }
}
qsort(array, arrayLength, sizeof(WordArray), cmpwfunc);

Any suggestions will be appreciated.


Solution

  • The problem with your second version is when A->freq and B->freq are not equal. In that case you can't just return -1. In that case you need to compare A->freq and B->freq like you did in the first function. So...

    Change

    else{
        return -1;
    }
    

    to

    return ( B->freq - A->freq );
    

    Or better - change it to

    if ( B->freq > A->freq ) return 1;
    return -1;