'qsort() not working for array of number

Actually i have to create huffman tree for that i need to sort the frequency and i am using qsort() function for that. But when i try to display the frequency it show still the same pattern (Not the sorted one). Here is my code:-

        struct node
        {
            int value;
            char letter;                 /* symbol */
            struct node *left,*right;    /* left and right subtrees */
        };
    typedef struct node Node;
//Given below is the frequency of all 27 alphabets
int englishLetterFrequencies [27] = {81, 15, 28, 43, 128, 23, 20, 61, 71, 2, 1, 40, 24, 69, 76, 20, 1, 61, 64, 91, 28, 10, 24, 1, 20, 1, 130};

here is my function where i try to build huffman (its inside the main() ):

/*builds the huffman tree and returns its address by reference*/

    void buildHuffmanTree(Node **tree){
        Node *temp;
        Node *array[27];
        int i, subTrees = 27;
        int smallOne;

        for (i=0;i<27;i++)
        {
            array[i] = malloc(sizeof(Node));
            array[i]->value = englishLetterFrequencies[i];
            array[i]->letter = i;
            array[i]->left = NULL;
            array[i]->right = NULL;
        }
         smallOne=sorting(array); //this function is responsible for sorting. I HAVE QSORT() CALL IN THIS FUNCTION

    return;
}

see its function definition :

int sorting(Node *array[])
{
    int smaller;
    int i = 0; int d,p;
    printf("the array frequency is \n");
    for(d=0;d < 27;d++)
    printf("%d  ",*array[d]);
    // sorting of arrays
    qsort(array,27,sizeof(*array),&cmpfunc); 
    //////////////////////////
    printf("\n the sorted array frequency is \n");
        for(p=0;p < 27;p++)
    printf("%d  ",*array[p]);

    return smaller;
}

whereas the cmpfunc() is here like this //PROBABLY MISTAKE IS HERE

 int cmpfunc (const void * a, const void * b)
    {
          return ( ((Node *)a)->value - ((Node *)b)->value );
    }

Any idea why it don't sort the arrays ?



Solution 1:[1]

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

This is casting a and b as "pointer-to-pointer-to-int", so by dereferencing them only once you then calculate the difference between two pointers. What you mean is:

 return ( (*(Node **)a)->value - (*(Node **)b)->value );

because whilst **(int**)a might work in this case it is massively confusing to anyone trying to understand the code.

Edit: sorry, I ended up missing a dereference there myself - fixed.

Also:

printf("%d  ",*array[d]);

should be

printf("%d  ",array[d]->value);

for the same reason.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1