计算根据伪代码实现的C中的排序,但不能正常运行

时间:2017-09-10 11:33:02

标签: c algorithm sorting

我已根据其伪代码(written on the blackboard in this video explanation)实现了计数排序,但由于一些神秘的原因,它似乎没有正确排序。

对于测试输入:10 9 8 7 6 5 4 3 2 1

它给出:3 4 5 6 7 8 1 0 0 9

这似乎是一个非常简单的问题,但我无法弄清楚为什么会发生这种情况。

git checkout branch_name

1 个答案:

答案 0 :(得分:3)

问题在于您分配计数器数组的顺序:当您编写

copy = (int*) malloc(sizeof(int) * max);

未设置max,因此其值未定义。因此,分配会产生未定义的行为,使您的程序无效。

您需要将分配移动到计算max的循环之后。分配max+1项,因为数组索引从零开始:

int max = array[0];
for(i=0;i<n;++i)
    if(array[i] > max)
        max = array[i];
copy = malloc(sizeof(int) * (max+1));

最后还需要free copyout以避免内存泄漏:

free(copy);
free(out);