I would do six changes:
- Better variable names, especially for the arguments
- Remove unnecessary temporary array
- Handle negative numbers
- Initialize temporary array with
memset
instead of a loop. - Comments with pre and post conditions
- Dynamically allocate the temporary array to avoid problems with the stack for large arrays.
The code looks like this:
/* Preconditions:
array is a pointer to the array that should be sorted
length is the number of elements in the array
Postconditions:
array is sorted
*/
void sort(int *array, size_t length) {
if(!array || length<1) return;
int max = array[0];
int min = max;
for (int i = 0; i < length; i++) {
if(max < array[i]) max = array[i];
if(min > array[i]) min = array[i];
}
const size_t range = max - min + 1;
intconst *tmpsize_t size = malloc(range * sizeof *array;
int *tmp = malloc(size);
if(!tmp) { /* Handle allocation error */ }
memset(tmp, 0, range * sizeof *tmpsize);
for (int i = 0; i < length; i++) tmp[array[i] - min]++;
int index = 0;
for (int i = 0; i < range; i++) {
for (int j = 0; j < tmp[i]; j++) {
array[index] = i + min;
index++;
}
}
free(tmp);
}