vendredi 12 mars 2021

How do I print my counter sorted array in C?

I am trying to Counter Sort a random array of single digit integers, but I cannot find a way to print the array once it has been sorted successfully.

Here is my Counter Sort function:

int CounterSort(int data[], int length)

// creating an integer array of size same as the input array size and initialize it to zero
int output[length];

memset(output, 0, sizeof(output));

int max = 0;

// to find the max element of the input array
int i;
for(i=0; i<length; ++i)
{
    if(data[i] > max)
        max = data[i];
}
// creating an integer array of size max and initialize it to zero
int temp[max];

memset(temp, 0, sizeof(temp));

// storing the count of each integer from the input array data[] by using that int as index in the temp[] array
for (i = 0; i < length; i++)
    temp[data[i]]++;

// calculating the starting index for each integer in the input array
int total = 0;
for (i = 0; i <= max; i++)
{
    int prevs_count = temp[i];

    temp[i] = total;

    total += prevs_count;
}

// copying the results to the output array preserving order of input array with same keys
for (i = 0; i < length; i++)
{
    output[temp[data[i]]] = data[i];
    temp[data[i]]++;
}

// checking if the output array is properly sorted.

for (i = 0; i < length-1; i++)
    if(output[i] > output[i+1])
        // if there is some failure return 0
        return 0;

// if properly sorted then return 1
return 1;

}`

..and here is my main function:

int main()

int no = 1;
int a;
int j;



// loop iterating as many times as given by user
for (a=0;a<no;a++)
{
        
        int size_arr = 1000;

        // initialize the input array and store random values in the input array
        int my_array[size_arr];
        
        srand(time(0));
        for (j = 0; j < size_arr; j++) {
            my_array[j] = rand()%10;
            printf("%d ",my_array[j]);
        }

        // check if sorting is successful.. if check is 0 then failure, if check is 1 then success
        int check =  CounterSort(my_array, size_arr);
            
        if (!check)
            printf("\nProblem in Sorting\n");
        else
            printf("\nSuccessful\n");
        
}

return 0;

} I believe the problem lies in the way that I generate the random numbers for the array, but I am not sure. Any help is appreciated.




Aucun commentaire:

Enregistrer un commentaire