diff --git a/.zed/debug.json b/.zed/debug.json index cff2839..48a4749 100644 --- a/.zed/debug.json +++ b/.zed/debug.json @@ -1,9 +1,9 @@ [ { - "label": "Debug td6 exo1", + "label": "Debug td6", "build": { "command": "gcc", - "args": ["-o", "./exe", "-lm", "-g", "td6/exo1.c"], + "args": ["-o", "./exe", "-lm", "-g", "td6/td6.c"], "cwd": "$ZED_WORKTREE_ROOT", }, "program": "$ZED_WORKTREE_ROOT/exe", diff --git a/td5/td5.c b/td5/td5.c index 24dff6e..eab21ae 100644 --- a/td5/td5.c +++ b/td5/td5.c @@ -82,7 +82,7 @@ const int sorted[] = {0, 0, 3, 5, 5, 9}; const int n = 6; int main() { - int t1[6]; + int t1[n]; memcpy(t1, t, n * sizeof(int)); insertion_sort(t1, n); assert(memcmp(t1, sorted, n * sizeof(int)) == 0); diff --git a/td6/exo1.c b/td6/exo1.c deleted file mode 100644 index c3704e0..0000000 --- a/td6/exo1.c +++ /dev/null @@ -1,57 +0,0 @@ -#include -#include - -void print_t(int t[], int len) { - printf("["); - for (int i = 0; i < len; i++) { - printf("%d,", t[i]); - } - printf("]\n"); -} - -void quicksort(int t[], int len) { - if (len < 2) { - return; - } - int ip = len / 2; - int p = t[ip]; - int a = 0; - int b = len - 1; - - while (a < b) { - while (t[a] < p && a < b) { - a++; - if (a >= ip) { - int tmp = t[a]; - t[a] = t[ip]; - t[ip] = tmp; - ip++; - a--; - } - } - while (t[b] > p && a < b) { - b--; - if (b <= ip) { - int tmp = t[b]; - t[b] = t[ip]; - t[ip] = tmp; - ip--; - b++; - } - } - int tmp = t[a]; - t[a] = t[b]; - t[b] = tmp; - a++; - b--; - } - quicksort(t, ip); - quicksort(t + ip + 1, len - ip - 1); -} - -int main() { - int t[] = {0, -7, 4, -2, 2, -3}; - quicksort(t, 6); - print_t(t, 6); - return 0; -} diff --git a/td6/td6.c b/td6/td6.c new file mode 100644 index 0000000..6471868 --- /dev/null +++ b/td6/td6.c @@ -0,0 +1,49 @@ +#include +#include +#include + +void printt(int t[], int n) { + printf("["); + for (int i = 0; i < n; i++) { + printf("%d,", t[i]); + } + printf("]\n"); +} + +void swap(int t[], int i, int j) { + int tmp = t[i]; + t[i] = t[j]; + t[j] = tmp; +} + +void quicksort(int t[], int n) { + if (n <= 1) { + return; + } + int a = 0; + int b = n - 1; + int p = t[n - 1]; + while (a < b) { + if (t[a] <= p) + a++; + else if (t[b] >= p) + b--; + else { + swap(t, a, b); + } + } + swap(t, b, n - 1); + quicksort(t, b); + quicksort(t + b + 1, n - b - 1); +} + +const int t[] = {5, 3, 9, 0, 5, 0}; +const int sorted[] = {0, 0, 3, 5, 5, 9}; +const int n = 6; + +int main() { + int t1[n]; + memcpy(t1, t, n * sizeof(int)); + quicksort(t1, n); + assert(memcmp(t1, sorted, n * sizeof(int)) == 0); +}