Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C-按计数排序,然后按字母顺序排序_C_Qsort - Fatal编程技术网

C-按计数排序,然后按字母顺序排序

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

我正在尝试运行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 *b1 = (Word *)c2;
    return (b1->freq - a1->freq);
}
我的qsort函数是:

qsort(words, count, sizeof(Word), compare);

但在我按频率排序之后,我不知道如何按字母顺序排序。

Richard,请注意以下几点:

  • 分配给非void指针时,我不强制转换void指针
  • 我不会为了它而使用typedef
  • 为了得到数组的长度,我将数组的大小除以数组中第一个元素的大小
  • 我在
    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