【问题标题】:Count Sort in C - incomplete sortingC中的计数排序 - 不完全排序
【发布时间】:2021-12-26 16:02:52
【问题描述】:

我正在尝试编写一个计数排序程序。我的问题是它似乎对前 4 个数字进行了排序,之后他只打印了 0。我的输入来自外部文件。

这是我的排序输出:

0 1 5 8 0 0 0 0 0 0 0 0 0 0 0 0 0

以下是我目前的代码:

int MAX_LAENGE = 1000;
int MAX_VALUE = 100;
int i, k, j;

void count_sort_calculate_counts(int input_array[], int len, int count_array[]) {
    for ( i = 0; i < len; i++)
    {
        count_array[i] = 0;
    }
    for (j = 0; j < len; j++)
    {
        count_array[input_array[j]] = count_array[input_array[j]] + 1;
    }
}

void count_sort_write_output_array(int output_array[], int len, int count_array[]) {
    k = 0;
    for (j = 0; j < len; j++)
    {
        for (i = 0; i < count_array[j]; i++)
        {
            output_array[k] = j;
            k = k + 1;
        }
    }

【问题讨论】:

  • len 表示 input_array 中的元素数或允许的最大值(即计数排序的限制)。看来您两者都使用它,这是错误的。另外请注意,这不是插入排序(正如您在问题中所说)
  • 更正了问题中的错字,谢谢! len 是数组中元素的数量。我可能需要在某个地方更换它,但我不知道在哪里以及用什么。

标签: c sorting


【解决方案1】:

两个周期 - 一个将计数设置为 0,另一个打印数字不应该在 len 之前,而是应该在 MAX_VALUE 之前。

for ( i = 0; i < MAX_VALUE; i++)
{
    count_array[i] = 0;
}

在打印数字的函数中类似:

for (j = 0; j < MAX_VALUE; j++)

没有更多关于如何使用此代码的上下文,这是我发现的唯一问题。

【讨论】:

  • 是的,这就是问题所在!非常感谢。
猜你喜欢
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 2019-09-29
  • 1970-01-01
相关资源
最近更新 更多