实际上,我必须创建霍夫曼树,因为我需要对频率进行排序,为此我使用了 qsort() 函数。 但是当我尝试显示频率时,它仍然显示相同的模式(不是排序的模式)。 这是我的代码:-
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};
这是我尝试构建 huffman 的函数(在 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;
}
查看其函数定义:
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;
}
而 cmpfunc() 在这里是这样的//这里可能有错误
int cmpfunc (const void * a, const void * b)
{
return ( ((Node *)a)->value - ((Node *)b)->value );
}
知道为什么它不对数组进行排序吗?
最佳答案
return ( (*(int**)a) - (*(int**)b ));
这是将 a
和 b
转换为“pointer-to-pointer-to-int”,因此只需对它们取消引用一次,即可计算两个指针之间的差异.你的意思是:
return ( (*(Node **)a)->value - (*(Node **)b)->value );
因为虽然 **(int**)a
在这种情况下可能有效,但它极大地让任何试图理解代码的人感到困惑。
编辑:抱歉,我自己在那里遗漏了一个取消引用 - 已修复。
还有:
printf("%d ",*array[d]);
应该是
printf("%d ",array[d]->value);
出于同样的原因。
关于c - qsort()不适用于数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20961094/