【问题标题】:Why does this merge sort code keeps giving me this weird output?为什么这个合并排序代码总是给我这个奇怪的输出?
【发布时间】: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

ScreenShot of the code and the output

【问题讨论】:

  • 谁告诉你cout &lt;&lt; a; 会是打印数组元素的方法?
  • 没有普遍接受的“正确方法”来打印数组的内容。见Printing an array in C++?
  • 旁注:int b[n] 是一个可变长度数组,它不是有效的 C++。它可能在某些编译器上作为非标准扩展被支持,但你应该忘记它。 using namespace std 和包含 bits/stdc++.h 也被认为是你应该避免的事情。
  • 为什么标题说“合并排序”而代码说“计数排序”(这是计数排序的无效实现)?你知道你想做什么吗?

标签: c++ mergesort


【解决方案1】:

您的代码有两个错误。

  1. 打印数组方法错误。
  2. CountSort 中的第三个循环错误。这个循环只工作一次。

有修复结果。

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 < n; 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  ->  ";
    for (int i = 0; i < 17; ++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 

【讨论】:

    【解决方案2】:

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

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

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

    或者

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

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 2021-12-09
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多