【问题标题】:sorting using qsort in c [closed]在c中使用qsort进行排序[关闭]
【发布时间】:2016-03-17 14:44:15
【问题描述】:

我在 c 中有这段代码

const char * array[] = {
    "1",
    "2",
    "helloworld",
    "worldhello",
    "3",
    "zzzzzzzzzz",
    "Zzzzzzzzzz",
    "zzzzzzzzzZ",

};

/* n_array is the number of elements in the array. */

#define n_array sizeof(array)/sizeof(const char *)

/* Compare the strings. */

static int compare (const void * a, const void * b)
{
    /* The pointers point to offsets into "array", so we need to
       dereference them to get at the strings. */

    return strcmp (*(const char **) a, *(const char **) b);
}

int main ()
{
    int i;
    qsort (array, n_array, sizeof (const char *), compare);
    for (i = 0; i < 50000; i++) {
        printf ("%d: %s.\n", i, array[i]);
    }
    return 0;
}

我希望输出变成这样

helloworld
worldhello
Zzzzzzzzzz
zzzzzzzzzz
zzzzzzzzzZ

我如何修改我的代码以获得输出

【问题讨论】:

  • 我喜欢你在 for 循环中的 i &lt; 50000。有什么有意义的输出吗?顺便说一句,你仍然有字符串“1”、“2”和“3”,所以你永远无法得到你想要的输出。
  • 只需依次打印每一个,就完成了。或者也许编辑您的问题,使其有意义。

标签: c sorting qsort


【解决方案1】:

有两个错误:

a) 对于compare 中的许多解引用指针,它实际上要简单得多:

static int compare (const void * a, const void * b) {
    return strcmp (a, b);
}

b) 你的输出循环,要达到 50000,真的吗?

    for (i = 0; i < n_array; i++) {
        printf ("%d: %s\n", i, array[i]);
    }

摆脱“1”、“2”、“3”是另一个练习。

【讨论】:

    【解决方案2】:

    因为'Z'小于'h',所以会排在第一位。

    您当然可以使用stricmp(或strcmpi),但现在带有 Z 或 z 的字符串将按任意顺序排序。

    然后是字符串“1”、“2”、“3”,你不能删除它们(实际上你可以,但不能通过排序)。

    所以你的愿望无法实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      相关资源
      最近更新 更多