You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++计数排序代码输出十六进制地址而非排序结果,哪里出错?

代码错误排查及修正方案

存在的错误列表

  • 循环条件逻辑错误:第三层遍历原数组填充结果数组的循环条件写错,原代码for (int i = 0; i >= 0; i--)只会执行1次就退出,仅处理了原数组第0个元素,完全没有完成排序逻辑。正确写法应该是倒序遍历整个原数组:for (int i = n - 1; i >= 0; i--),倒序遍历还可以保证计数排序的稳定性。
  • 数组输出逻辑错误:直接对数组名a执行cout输出,C++中数组名会隐式转换为首元素的指针,因此输出的是数组的内存地址而非数组元素,需要循环遍历数组逐个输出元素。
  • 不符合C++标准语法问题:代码中int count[k + 1]={0}和int b[n]属于可变长度数组(VLA),是GCC的扩展语法,不属于标准C++规范,在MSVC等编译器下无法编译通过,建议使用vector替代或者动态申请内存。

修正后的完整代码

#include <iostream>
#include <vector>
using namespace std;

void CountSort(int a[], int n, int k)
{
    vector<int> count(k + 1, 0);
    vector<int> b(n);

    for (int i = 0; i < n; i++)
    {
        ++count[a[i]];
    }
    for (int i = 1; i <= k; i++)
    {
        count[i] += count[i - 1];
    }
    // 修正循环条件,倒序遍历原数组
    for (int i = n - 1; i >= 0; i--)
    {
        b[count[a[i]] - 1] = a[i];
        --count[a[i]];
    }
    for (int i = 0; i < n; i++)
    {
        a[i] = b[i];
    }
}

int main()
{
    int a[] = {2, 1, 1, 0, 2, 5, 4, 0, 2, 8, 7, 7, 9, 2, 0, 1, 9};
    int n = 17;
    CountSort(a, n, 9);
    cout << "The sorted array is  ->  ";
    // 修正输出逻辑,遍历输出每个元素
    for (int i = 0; i < n; i++)
    {
        cout << a[i] << " ";
    }
    cout << endl;
    return 0;
}

运行结果

The sorted array is  ->  0 0 0 1 1 1 2 2 2 2 4 5 7 7 8 9 9 

内容的提问来源于stack exchange,提问作者user16919302

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:57:02