My own algorithm to sort integers I'm studying the C language with a Harvey Deitel book.

Trying to solve an exercise that asked to write a good sorting algorithm, I did this:

void sort(int v[], int d){

int max = 0;
for(int i = 0; i &lt; d; i++){
    if(v[i] &gt; max)max = v[i];
}

int v2[max+1];  
int v3[max+1];  
for(int i = 0; i &lt; max+1; i++){
    v2[i] = -1;
    v3[i] = 0;
}

for(int i = 0; i &lt; d; i++){
    if(v3[v[i]] == 0){
        v2[v[i]] = v[i];
        v3[v[i]]++;
    }
    else {
        v3[v[i]]++;
    }
}

int j = 0;
for(int i = 0; i &lt; max+1; i++){
    if(v2[i] != -1){
        for(int k = 0; k &lt; v3[i]; k++){
            v[j] = v2[i];
            j++;
        }
    }
}
}
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&lt;1) return;

    int max = array[0];
    int min = max;

    for (int i = 0; i &lt; length; i++) {
        if(max &lt; array[i]) max = array[i];
        if(min &gt; array[i]) min = array[i];
    }

    const size_t range = max - min + 1;
    const size_t size = range * sizeof *array;
    int *tmp = malloc(size);
    if(!tmp) { /* Handle allocation error */ }
    memset(tmp, 0, size);

    for (int i = 0; i &lt; length; i++) tmp[array[i] - min]++;

    int index = 0;
    for (int i = 0; i &lt; range; i++) {
        for (int j = 0; j &lt; tmp[i]; j++) {
                array[index] = i + min;
                index++;
        }
    }
    free(tmp);
}