C-按计数排序,然后按字母顺序排序
我正在尝试运行qsort,首先按数字排序,然后按字母顺序排序。数组字是:C-按计数排序,然后按字母顺序排序,c,qsort,C,Qsort,我正在尝试运行qsort,首先按数字排序,然后按字母顺序排序。数组字是: COPY 3 CLOSER 2 TAUGHT 2 AW 2 LOOKS 2 SHAD 3 HA 3 结构是: typedef struct { char word[101]; int freq; } Word; 到目前为止,我的比较功能是: int compare(const void *c1, const void *c2){ Word *a1 = (Word *)c1; Word
COPY 3
CLOSER 2
TAUGHT 2
AW 2
LOOKS 2
SHAD 3
HA 3
结构是:
typedef struct {
char word[101];
int freq;
} Word;
到目前为止,我的比较功能是:
int compare(const void *c1, const void *c2){
Word *a1 = (Word *)c1;
Word *b1 = (Word *)c2;
return (b1->freq - a1->freq);
}
我的qsort函数是:
qsort(words, count, sizeof(Word), compare);
但在我按频率排序之后,我不知道如何按字母顺序排序。Richard,请注意以下几点:
struct word
比较单词中的频率。为了推导顺序,我实际上使用if,else if,else。根据操作数的不同,简单地减去整数可能会有奇怪的行为
const
指针,以强制实现不变性Richard,你的比较功能需要更加复杂。比较频率和字符串…如果单词的频率相同,则需要比较单词<代码>如果(b1->freq!=b2->freq)返回(b1->freq-b2->freq),否则返回strcmp(b1->word,b2->word)代码>@JonathanLeffler为什么不把答案写成答案?你把一些变量的名字弄混了。是的,我把名字弄混了,因为问题中的名字不一致。即使名字已经确定,也没有足够的文本值得转换成答案。(或者,如果你愿意,“我很懒,没有看到足够的好处来提供答案”,不仅仅是因为我必须写更多的东西才能让它成为一个我可以接受的答案。)我想我需要更多:)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct word {
char *str;
int freq;
};
int compare_words(const void *a, const void *b)
{
const struct word *w1 = a;
const struct word *w2 = b;
int order;
if (w2->freq > w1->freq) {
order = 1;
} else if (w2->freq < w1->freq) {
order = -1;
} else {
order = strcmp(w1->str, w2->str);
}
return order;
}
int main(int argc, char const *argv[])
{
struct word mywords[] = {
{ "BAR", 2 },
{ "BAS", 2 },
{ "ACK", 2 },
{ "FOO", 8 },
{ "ZIP", 1 }
};
int len = sizeof(mywords) / sizeof(mywords[0]);
qsort(mywords, len, sizeof(mywords[0]), compare_words);
int i;
for (i = 0; i < len; i++) {
struct word w = mywords[i];
printf("%s\t%d\n", w.str, w.freq);
}
return 0;
}
FOO 8
ACK 2
BAR 2
BAS 2
ZIP 1