【问题标题】:Array initialization problem in count sort algorithm计数排序算法中的数组初始化问题
【发布时间】:2022-06-10 18:11:12
【问题描述】:

在给定的代码中,countsort 函数计算输入数组中的最大元素并将该值赋给变量 k。 之后,它初始化了一个包含 k 个元素的计数数组,代码运行没有任何错误,但没有输出。 但是,当我将 int count[k]={0} 更改为 int count[10]={0} 时,代码运行并给出输出。

这是代码,我对第 10 行感到困惑。

#include <iostream>
using namespace std;
void countsort(int a[], int n)
{
    int k = a[0];
    for (int i = 0; i < n; i++)
    {
        k = max(k, a[i + 1]);
    }
    int count[10] = {0}; // when i change this 10 wiht k the code dosent throw any output.
    for (int i = 0; i < n; i++)
    {
        count[a[i]]++;
    }
    for (int i = 1; i <= k; i++)
    {
        count[i] += count[i - 1];
    }
    int output[n];
    for (int i = n - 1; i >= 0; i--)
    {
        output[--count[a[i]]] = a[i];
    }
    for (int i = 0; i < n; i++)
    {
        a[i] = output[i];
    }
}

int main()
{
    int a[] = {1, 3, 2, 3, 7, 1, 6, 4, 3};
    countsort(a, 9);
    for (int i = 0; i < 9; i++)
    {
        cout << a[i] << " ";
    }
    return 0;
}

有人能解释一下为什么会这样吗,在此先感谢。

【问题讨论】:

  • 可变长度数组不是标准的 C++ 特性。

标签: c++ arrays


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-01
  • 1970-01-01
相关资源
最近更新 更多