I have a problem with Counting sort. When i will sort table sometimes it work but sometimes no (It doesn’t work when k == size) and i don’t know why. Please help. This is my code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define MAX 100000
int tabA[MAX];
int tabB[MAX];
int tabC[MAX];
int k;
void scope(int size){
int i, max = 0, min;
min = tabA[1];
for(i = 1; i <= size; i++){
if(tabA[i] > max)
max = tabA[i];
if(tabA[i] < min)
min = tabA[i];
}
k = max - min + 1;
}
void rand1(int size){
int i;
srand(time(NULL));
for(i = 0; i <= size; i++)
tabA[i] = rand() % 8;
}
void countingsort(int size){
int i;
for(i = 0; i < k; i++)
tabC[i] = 0;
for(i = 0; i < size; i++)
tabC[tabA[i + 1]] = tabC[tabA[i + 1]] + 1;
for(i = 1; i <= k; i++)
tabC[i] = tabC[i] + tabC[i - 1];
for(i = size; i >= 1; i--){
tabB[tabC[tabA[i]]] = tabA[i];
tabC[tabA[i]] = tabC[tabA[i]] - 1;
}
}
int main(void){
int size, i;
printf("Please write how many numbers you wont to sort: ");
scanf("%d", &size);
rand1(size);
scope(size);
countingsort(size);
printf("Numbers to sort:\n");
for(i = 1; i <= size; i++)
printf("%d\n", tabA[i]);
printf("\nK: %d\n\n", k);
printf("Sorting numbers:\n");
for(i = 1; i <= size; i++)
printf("%d\n", tabB[i]);
return 0;
}
Thank’s for all help.
At least this code:
Has the problem, that in the first, intialization loop
igoes0..k-1, but in the last loopigoes from1..k, while assumingtabCis initialized. Also, middle loop assumes range oftabAvalues is0..k, which it might not be (looking at randomization function, it actually probably is, but this is just co-incidence I suppose).