From c0aaecda45ef1503be3049e7bcf1a0f42e6f4312 Mon Sep 17 00:00:00 2001 From: Arkitu Date: Mon, 12 Jan 2026 22:32:07 +0100 Subject: [PATCH] td5 exo4 --- td5/td5.c | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/td5/td5.c b/td5/td5.c index 21b05d4..24dff6e 100644 --- a/td5/td5.c +++ b/td5/td5.c @@ -1,5 +1,6 @@ #include #include +#include #include void printt(int t[], int n) { @@ -11,7 +12,6 @@ void printt(int t[], int n) { } // Exercice 1 - void insertion_sort(int t[], int n) { for (int i = 0; i < n; i++) { int x = t[i]; @@ -23,7 +23,6 @@ void insertion_sort(int t[], int n) { t[j + 1] = x; } } - void selection_sort(int t[], int n) { for (int i = 0; i < n; i++) { int min = t[i]; @@ -39,6 +38,7 @@ void selection_sort(int t[], int n) { } } +// Exercice 2 void cocktail_sort(int t[], int n) { for (int i = 0; i < n / 2; i++) { for (int j = i; j < n - i - 1; j++) { @@ -58,6 +58,25 @@ void cocktail_sort(int t[], int n) { } } +// Exercice 4 +void counting_sort(int t[], int n, int k) { + int *counts = malloc(k * sizeof(int)); + for (int i = 0; i < k; i++) { + counts[i] = 0; + } + for (int i = 0; i < n; i++) { + counts[t[i]] += 1; + } + int len = 0; + for (int i = 0; i < k && len < n; i++) { + for (int j = 0; j < counts[i]; j++) { + t[len] = i; + len++; + } + } + free(counts); +} + const int t[] = {5, 3, 9, 0, 5, 0}; const int sorted[] = {0, 0, 3, 5, 5, 9}; const int n = 6; @@ -74,6 +93,9 @@ int main() { memcpy(t1, t, n * sizeof(int)); cocktail_sort(t1, n); - printt(t1, n); + assert(memcmp(t1, sorted, n * sizeof(int)) == 0); + + memcpy(t1, t, n * sizeof(int)); + counting_sort(t1, n, 10); assert(memcmp(t1, sorted, n * sizeof(int)) == 0); }