You are viewing a single comment's thread. Return to all comments →
My C code with optimisation
int* countingSort(int arr_count, int* arr, int* result_count) { // Trouver la valeur maximale dans le tableau pour optimiser la taille de "result" int max_val = 0; for (int i = 0; i < arr_count; i++) { if (arr[i] > max_val) { max_val = arr[i]; } } // Allouer de la mémoire pour le tableau de comptage int* result = (int*)calloc(max_val + 1, sizeof(int)); if (result == NULL) { fprintf(stderr, "allocation failed\n"); exit(EXIT_FAILURE); } // Remplir le tableau de comptage for (int i = 0; i < arr_count; i++) { result[arr[i]]++; } // Allouer de la mémoire pour le tableau trié int* sortedArray = (int*)malloc(arr_count * sizeof(int)); if (sortedArray == NULL) { fprintf(stderr, "allocation failed\n"); exit(EXIT_FAILURE); } // Remplir le tableau trié en fonction des occurrences int j = 0; for (int i = 0; i <= max_val; i++) { while (result[i] > 0) { sortedArray[j++] = i; result[i]--; } } *result_count = arr_count; free(result); return sortedArray; }
Seems like cookies are disabled on this browser, please enable them to open this website
Counting Sort 2
You are viewing a single comment's thread. Return to all comments →
My C code with optimisation