【问题标题】:C - Qsort By Count then AlphabeticallyC - Qsort 按计数然后按字母顺序
【发布时间】:2018-09-22 02:16:55
【问题描述】:

我正在尝试运行 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,您的比较功能需要更复杂。比较频率和字符串...
  • 如果单词出现的频率相同,则需要比较单词。 if (b1->freq != b2->freq) return (b1->freq - b2->freq) else return strcmp(b1->word, b2->word);.
  • @JonathanLeffler 为什么不把答案写成答案?不过,你在那里混淆了一些变量名。
  • 是的,我混淆了名称,因为问题中的名称不一致。即使名称已修复,也不足以将其转换为答案。 (或者,如果您愿意,“我很懒,没有看到提供答案的足够好处”,尤其是因为我必须写更多才能使它成为我可以接受的答案。)
  • 我猜对我来说更多:)

标签: c qsort


【解决方案1】:

Richard,请注意以下几点:

  1. 分配给非 void 指针时,我不强制转换 void 指针
  2. 我不是为了它而使用 typedef
  3. 为了得到数组的长度,我用数组的大小除以数组中第一个元素的大小
  4. 我在struct word 中使用char *
  5. 我不会简单地减去compare_words 中的频率。为了推导顺序,我实际上使用了 if、else if、else。根据操作数,简单地减去整数可能会产生奇怪的行为。
  6. 我在比较函数中维护const 指针,以强制执行不变性。

代码:

#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

【讨论】:

    猜你喜欢
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    相关资源
    最近更新 更多