I have been trying to implement counting sort.
It requests the user for the number of times the program should run n.
The number of elements which will be sorted sz and the element with the maximum value k. Though the program runs correctly with n = 1, i.e. running it once, in other cases I get an error.
#include <stdio.h>
#include <stdlib.h>
void cntsrt(int a[], int b[], int k);
int sz;
int main(int argc, char **argv) {
int n, k,*b, *a, i, j;
scanf("%d", &n);
while (n--) {
scanf("%d", &sz);
scanf("%d", &k);
a = (int *) calloc(sz + 1, sizeof(int));
for (i = 1; i <= sz; i++)
scanf("%d", &a[i]);
b = (int *) calloc(sz + 1, sizeof(int));
cntsrt(a, b, k);
printf("\n");
for (j = 1; j <= sz; j++)
printf("\t%d", b[j]);
free((void*)a);
free((void*)b);
}
printf("\n");
return 0;
}
void cntsrt(int a[], int b[], int k) {
int i, j,*c;
c = (int*) malloc(k*(sizeof(int)));
for (i = 0; i <= k; i++)
c[i] = 0;
for (j = 1; j <= sz; j++)
c[a[j]] = c[a[j]] + 1;
for (i = 1; i <= k; i++)
c[i] = c[i] + c[i - 1];
for (j = 8; j > 0; j--) {
b[c[a[j]]] = a[j];
c[a[j]] = c[a[j]] - 1;
}
}
Array index should start from 0 to sz.
Int the function
cntsrt–If the length of the array is n, then it’s accessible indexes are from 0 to n-1.