首页 > 解决方案 > 为什么这个合并排序代码总是给我这个奇怪的输出?

问题描述

我写了计数排序代码,但它显示了奇怪的输出,你能告诉我哪里错了吗?

#include <bits/stdc++.h>
using namespace std;

void CountSort(int a[], int n, int k)
{
    int count[k + 1]={0};
    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 = 0; 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};
    CountSort(a, 17, 9);
    cout<<"The sorted array is  ->  "<<a;
    return 0;
}

它给出这样的输出 -

The sorted array is  ->  0x7bfdd0

代码和输出的屏幕截图

标签: c++mergesort

解决方案


尝试打印数组时,不能只使用std::cout << a. 目前您的代码正在打印数组的内存地址a,这不是您想要的。

要解决此问题,请一一打印数组的所有元素。这些循环可能会有所帮助:

for (const auto& elem : a)
    std::cout << elem << " ";

或者

for (int i = 0; i < sizeof(a) / sizeof(int); i++)
    std::cout << a[i] << " ";

推荐阅读