我一直在努力执行计票。
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("
");
for (j = 1; j <= sz; j++)
printf(" %d", b[j]);
free((void*)a);
free((void*)b);
}
printf("
");
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;
}
}