I 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;
}
size+1when it should be usingmax+1.