计数排序我的输入是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

本文关键字:输入 不正确 输出 排序 我的      更新时间:2023-10-16
#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中未初始化元素的垃圾。)

顺便说一下,在C中,倒数时先递减是一个经常发生的事情,这是由于数组的上界是排他的。你的循环可以这样写:
for (i = n; i-- > 0; ) {
    C[A[i]] = C[A[i]] - 1;
    B[C[A[i]]] = A[i];
}

缺少更新部分,因为减量发生在进入循环体之前。你不用在初始化中减去1。