Home > Net >  I want to print a sorted array in C using count sort but my code is not working
I want to print a sorted array in C using count sort but my code is not working

Time:09-14

enter image description hereI want to print a sorted array in C using count sort but my code is not working ! I watched a tutorial of the countsort algorithm and copied the code from the video but for some reason my code is not working while the code runs in the video . I also wrote comments based on the work that the part of the code is doing in this script. The output should be the given array and a sorted array on next line

#include<stdio.h>
#include<limits.h>
#include<stdlib.h>

void displayArray(int *arr,int size){
    printf("[ ");
    for(int i=0; i<size; i  ){
        printf("%d ",arr[i]);
    }
    printf("]\n");
}

int maximum(int A[], int size){
    int max = INT_MIN;
    for(int i=0; i<size; i  ){
        if(max < A[i]){
            max = A[i];
        }
    }
    return max;
}

void countSort(int* A, int size){
    int i,j;

    // Find the maximum element in Array
    int max = maximum(A,size);

    // Create the count array
    int* count = (int*) malloc((max 1)*sizeof(int));

    // Initialize the count array elements to zero
    for(i=0; i < size 1; i  ){
        count[i] = 0;
    }

    // Increment the corrosponding index in the count array
    for(i=0; i<size; i  ){
        count[A[i]] = count[A[i]]   1;
    }

    i = 0;  // Counter for count array
    j = 0;  // Counter for given array

    while(i <= max){
        if(count[i] > 0){
            A[j] = i;
            count[i] = count[i] - 1;
            j  ;
        }
        else{
            i  ;
        }
    }
}

int main(){
    int A[] = {56,23,53,13,64,34};
    int n = 6;
    displayArray(A,n);
    countSort(A,n);
    displayArray(A,n);
    return 0;   
}

CodePudding user response:

This loop

// Initialize the count array elements to zero
for(i=0; i < size 1; i  ){
    count[i] = 0;
}

does not set all elements of the dynamically allocated array to zeroes.

It seems you mean

// Initialize the count array elements to zero
for(i=0; i < max 1; i  ){
    count[i] = 0;
}

Or if to include the header <string.h> then you can write

memset( count, 0, ( max   1 ) * sizeof( int ) );

Or you could initially allocate and initialize the array with zeroes using standard function calloc instead of malloc.

Pay attention to that the code will not work if the array contains negative numbers.

  • Related