【问题标题】:Why is this counting sort in C++ not working?为什么 C++ 中的这种计数排序不起作用?
【发布时间】:2021-11-13 16:21:47
【问题描述】:

为什么这种计数排序不起作用?

#include <bits/stdc++.h>

using namespace std;

void countSort(vector<int>& input)
{
    int max = *max_element(input.begin(), input.end());
    vector<int> counter(max + 1);
    vector<int> output;
    for(int i = 0; i < max + 1; ++i)
    {
        counter[i] = 0;
    }

    for(int i = 0; i < input.size(); ++i)
    {
        counter[input[i]]++;
    }

    for(int i = 0; i < max  + 1; ++i)
    {
        while(counter[i] > 0)
        {
            output.push_back(counter[input[i]]);
            counter[i]--;
        }
    }
}

int main()
{
    vector<int> array = {9, 8, 9, 1, 5, 7, 1, 2};
    countSort(array);
}

当我运行此代码时,它只会向我发送一条错误消息,

进程以退出代码 1073741819 (0xC0000005) 结束

但我不明白错误在哪里。

【问题讨论】:

  • 在你的最后一个 for 循环中,input[i] 似乎假设 input 至少有 max+1 元素。但事实并非如此。错字?
  • @DrewDormann 在最后一个 for 循环中我只是通过了具有 max+1 个元素的计数器数组。怎么了?
  • 如果您使用g++clang++ 在编译时添加参数-g -fsanitize=address,undefined。运行程序时你会得到something like this。真的很有帮助
  • 不相关:不需要将counter 中的所有元素设置为0 的循环。
  • 错误信息是什么?

标签: c++ algorithm function loops sorting


【解决方案1】:

主要问题在于您的push_back

output.push_back(counter[input[i]]);

应该是:

output.push_back(i);

您也不保存已排序的output 数组的结果。您可以退货或更换input。在下面的示例中,我将替换 input

另一个潜在问题是您正在对 signed 整数进行排序,因此您应该期待负数。如果您现在得到一个负值,您将越界访问您的 counter 数组。

一个简单的补救措施是先检查minmax 的值,然后从counter 中的所有下标中减去min

例子:

#include <algorithm>
#include <iostream>
#include <vector>

void countSort(std::vector<int>& input) {
    auto[minit, maxit] = std::minmax_element(input.begin(), input.end());
    auto min = *minit;
    auto max = *maxit;
    std::vector<int> counter(max - min + 1);

    for(auto in : input) ++counter[in-min];           // -min offset

    input.clear(); // clearing it to fill with the sorted values

    for(int i = min; i <= max; ++i) {
        for(;counter[i-min] > 0; --counter[i-min]) {  // -min offset
            input.push_back(i);
        }
    }
}

int main() {
    std::vector<int> array = {9, 8, 9, 1, 5, 7, 1, 2, -10}; // negative value added
    
    countSort(array);

    for(auto v : array) std::cout << v << ' ';
}

输出:

-10 1 1 2 5 7 8 9 9

【讨论】:

    猜你喜欢
    • 2017-08-25
    • 2021-07-06
    • 2019-10-11
    • 2019-07-31
    • 2011-02-18
    • 2016-10-09
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    相关资源
    最近更新 更多