【发布时间】:2021-09-15 13:47:34
【问题描述】:
我写了计数排序代码,但它显示了奇怪的输出,你能告诉我哪里错了吗??
#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
【问题讨论】:
-
谁告诉你
cout << a;会是打印数组元素的方法? -
没有普遍接受的“正确方法”来打印数组的内容。见Printing an array in C++?
-
旁注:
int b[n]是一个可变长度数组,它不是有效的 C++。它可能在某些编译器上作为非标准扩展被支持,但你应该忘记它。using namespace std和包含 bits/stdc++.h 也被认为是你应该避免的事情。 -
为什么标题说“合并排序”而代码说“计数排序”(这是计数排序的无效实现)?你知道你想做什么吗?