c++counting-sort

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


when I trying to implement the counting sort I got this error " the problem caused the program to stop working correctly Windows will close the program and notify you if a solution is available "

 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


Solution

  • Fixed code (negative values are still not supported):

     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;
    }