c++ - 为什么这个合并排序代码总是给我这个奇怪的输出?
问题描述
我写了计数排序代码,但它显示了奇怪的输出,你能告诉我哪里错了吗?
#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
解决方案
尝试打印数组时,不能只使用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] << " ";
推荐阅读
- java - Cucumber 并行测试在本地运行良好,但在 Jenkins 上抛出 NPE
- ruby-on-rails - 如何在 ruby gem 中包含 ActionView::Helpers::TagHelper ...?使用 content_tag
- c++ - SFINAE 模板专业化不起作用
- python - 修复 subprocess.py 文件错误:找不到文件?
- python - 如何在电报机器人中同时管理多个用户请求?
- javascript - 代码崩溃,因为对象的 .rad 属性变得未定义
- excel - 将记录集导出到 Excel
- react-native - SyntaxError: Unexpected identifier - React Enzyme 测试中的无意义错误
- c++ - 为什么当“this”是指向 const 的指针时,返回类型必须是常量引用而不是简单引用?
- android - 如何将android应用程序传输到PC进行存储