计数排序我的输入是1,4,3,1但输出是垃圾值1,1,3输入不正确
Counting Sort My input is 1,4,3,1 But output is garbage value,1,1,3 Input is not not correct
#include<stdio.h>
#include<stdlib.h>
main()
{
int A[200],p=0,r=0,s=0,i,n,temp=0,B[200];
printf("Enter no. of Element for counting sort :");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
printf("nBefore Sorting: ");
for(i=0;i<n;i++)
printf("%d ",A[i]);
printf("n");
for(i=0;i<n;i++)
{
if(A[i]>temp)
temp=A[i];
}
printf("nLargest %d n",temp);
counting_sort(A,B,n,temp);
for(i=0;i<n;i++)
printf("%d ",B[i]);
printf("n");
}
counting_sort(int A[],int B[],int n,int temp)
{
int i=0,C[200],j;
for(i=0;i<=temp;i++)
C[i]=0;
for(i=0;i<n;i++)
C[A[i]]=C[A[i]]+1;
for(i=1;i<=temp;i++)
C[i]=C[i]+C[i-1];
for(i=n-1;i>=0;i--)
{
B[C[A[i]]]=A[i];
C[A[i]]=C[A[i]]-1;
}
}
好了,纸笔时间到了。你的输入是:
A = {1, 4, 3, 1}
您的计数已正确确定:
C' = {0, 2, 0, 1, 1}
然后将其转换为累计计数:
C = {0, 2, 2, 3, 4}
这一步也是正确的。这个数组代表什么?对于A
中的每个元素a
, C[a]
是该元素在所有a
s之后的索引,B
:
i 0 1 2 3 4
B[i] 1 1 3 4 <
对于不在A
中的元素也是如此:C[2]
为2。在1之后有一个0个2的(虚)块,该块之后的索引为2。
因为索引是块之后的索引,所以在使用它之前必须递减索引:
for (i = n - 1; i >= 0; i--) {
C[A[i]] = C[A[i]] - 1;
B[C[A[i]]] = A[i];
}
否则,当处理元素4时,最终将写入索引4,但该索引超出了数组的限制。(您看到的数字只是来自B
中未初始化元素的垃圾。)
for (i = n; i-- > 0; ) {
C[A[i]] = C[A[i]] - 1;
B[C[A[i]]] = A[i];
}
缺少更新部分,因为减量发生在进入循环体之前。你不用在初始化中减去1。
相关文章:
- 使用2个键的cpp-stl::优先级队列排序不正确
- 正弦级数方程计算不正确
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 密码登录程序将永远循环并显示不正确的结果
- 打印时有二叉树问题.用户输入不打印任何内容
- 在C++中返回不正确的楼层函数值
- 形状对象的旋转和缩放不正确C++
- C++ 读取文件读取文件不正确
- 关于类的 Python 文档 - 对C++的引用不正确
- 对于代码中指定的边界之外的值,对角差算法的输入不正确
- 使用 Get 的 C++ 输入被替换为空格、不正确的数字
- 当我输入分数值时,它返回不正确的结果
- 检查用户输入是否正确的函数不起作用
- 在具有 64 位 CPU 的 32 位 Win8 上运行 32 位 Orwell Dev-C++ - 输入指针返回不正确
- 计数排序我的输入是1,4,3,1但输出是垃圾值1,1,3输入不正确
- 我的 for 循环第一次正确输入,但第二次不正确,并显示第二个输入的输出。我不明白为什么会这样。
- 使用鞋帮不正确?直到我输入密码
- 如何处理不正确的输入文件
- 不正确的输入和读取
- 如何让C++忽略不正确的输入