Arrays 计数排序,排序数组的索引0

Arrays 计数排序,排序数组的索引0,arrays,algorithm,sorting,Arrays,Algorithm,Sorting,我有一个关于计数排序算法的问题。我阅读了有关它的文章,并在一个例子中一步一步地分析了它的代码,但我认为我一点也不了解。。如果我理解正确的话,为了让算法工作,你根本不应该使用排序数组的索引0,或者它只是算法的这个实现,不使用它 以下是实施的示例: /*Lets say that we have the following array initialized, k is the maximum value and n is the length of the array*/ int A[] =

我有一个关于计数排序算法的问题。我阅读了有关它的文章,并在一个例子中一步一步地分析了它的代码,但我认为我一点也不了解。。如果我理解正确的话,为了让算法工作,你根本不应该使用排序数组的索引0,或者它只是算法的这个实现,不使用它

以下是实施的示例:

/*Lets say that we have the following array initialized,
  k is the maximum value and n is the length of the array*/
int A[] = {4,5,1,3,7};
    k = 7;
    n = 5;

void Counting_sort(int A[], int k, int n)
{   
    /*C is the count array and B is the sorted array*/
    int i, j;
    int B[n], C[k+1];
    for(i = 0; i <=  k; i++)
        C[i] = 0;

    for(j = 0; j < n; j++)
        C[ A[j] ] = C[ A[j] ] + 1;

    for(i = 1; i < k+1; i++)
        C[i] = C[i] + C[i-1];

    for(j = 0; j < n; j++) {
        B[ C [ A [j] ] ] = A[j];
        C[ A[j] ] = C[ A[j]] - 1;
    }
    //so in this loop I must always traverse from 1 to <= n and leave the Index 0?
    for (i = 1; i <= n; i++)
        cout << B[i] << endl;
}
/*假设我们初始化了以下数组,
k是最大值,n是数组的长度*/
int A[]={4,5,1,3,7};
k=7;
n=5;
无效计数_排序(int A[],int k,int n)
{   
/*C是计数数组,B是排序数组*/
int i,j;
int B[n],C[k+1];

对于(i=0;i您的实现中有一个bug;也就是说,您将B初始化为大小n,但随后寻址B[n]

无论如何,如果要从B中的索引0开始,则需要更改:

B[C[A[j]]=A[j]

B[C[A[j]]-1]=A[j]

以及后续的for循环

对于(i=1;i 在B中从索引1开始的原因是,在索引处放置的最小元素等于要放置的元素的剩余数量的计数,也就是说,最小元素的最后一个放置在索引1处