当我尝试实现计数排序时出现此错误“该问题导致程序停止正常工作 Windows

when I trying to implement the counting sort I got this error " the problem caused the program to stop working correctly Windows

当我尝试实现计数排序时出现此错误“问题导致程序停止正常工作Windows将关闭程序并在有可用解决方案时通知您“

 void CountingSort(int *A,int size) {
    

    int SizeC = Max(A, size);
    int* B = new int[size];
    int* C = new int[SizeC+1];
    for (int i = 0; i < SizeC; i++) {
        C[i] = 0;

    }

    for (int i = 0; i < size; i++) {
    
    
        C[A[i]]++ ;
    
    }

    for (int  i = 0; i <SizeC; i++)
    {

        C[i] += C[i - 1];
    }

    for (int j = size - 1; j >= 0; j--) {
         

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

    }

    for (int i = 0; i < size; i++) {
        cout << B[i] << "\t" << endl;
    
    
    }



    delete[] C;
    delete[] B;
}

this is the error

  • i < SizeCi <SizeC 应该是 i <= SizeC。否则,值 SizeC 的元素将不会被正确处理。
  • C[i] += C[i - 1];i = 0 将导致 C[-1] 的读取超出范围。对应for循环的初始化应该是int i = 1,而不是int i = 0.
  • 递减 C[A[j]] --; 应该在 B[C[A[j]]] = A[j]; 之前发生,否则会发生 B[size] 的超出范围写入。
  • 当数组 A 包含负值时,此程序无法正常运行。

固定码(仍不支持负值):

 void CountingSort(int *A,int size) {
    

    int SizeC = Max(A, size);
    int* B = new int[size];
    int* C = new int[SizeC+1];
    for (int i = 0; i <= SizeC; i++) {
        C[i] = 0;

    }

    for (int i = 0; i < size; i++) {
    
    
        C[A[i]]++ ;
    
    }

    for (int  i = 1; i <= SizeC; i++)
    {

        C[i] += C[i - 1];
    }

    for (int j = size - 1; j >= 0; j--) {
         
        C[A[j]] --;

        B[C[A[j]]] = A[j];
        
    }

    for (int i = 0; i < size; i++) {
        cout << B[i] << "\t" << endl;
    
    
    }



    delete[] C;
    delete[] B;
}