td5 exo1 et exo2
This commit is contained in:
parent
f24f834ae0
commit
1a07fc21f6
@ -10,4 +10,15 @@
|
||||
"request": "launch",
|
||||
"adapter": "CodeLLDB",
|
||||
},
|
||||
{
|
||||
"label": "Debug td5",
|
||||
"build": {
|
||||
"command": "gcc",
|
||||
"args": ["-o", "./exe", "-lm", "-g", "td5/td5.c"],
|
||||
"cwd": "$ZED_WORKTREE_ROOT",
|
||||
},
|
||||
"program": "$ZED_WORKTREE_ROOT/exe",
|
||||
"request": "launch",
|
||||
"adapter": "CodeLLDB",
|
||||
},
|
||||
]
|
||||
|
||||
10
td5/exo1.c
10
td5/exo1.c
@ -1,10 +0,0 @@
|
||||
#include "stdio.h"
|
||||
#include "stdlib.h"
|
||||
|
||||
void intertion_sort(int t[], int n) {
|
||||
for (int i = 1; i < n; i++) {
|
||||
int j = 0;
|
||||
while (j < i && t[j] <= t[i])
|
||||
j++;
|
||||
}
|
||||
}
|
||||
79
td5/td5.c
Normal file
79
td5/td5.c
Normal file
@ -0,0 +1,79 @@
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
void printt(int t[], int n) {
|
||||
printf("[");
|
||||
for (int i = 0; i < n; i++) {
|
||||
printf("%d,", t[i]);
|
||||
}
|
||||
printf("]\n");
|
||||
}
|
||||
|
||||
// Exercice 1
|
||||
|
||||
void insertion_sort(int t[], int n) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
int x = t[i];
|
||||
int j = i - 1;
|
||||
while (j >= 0 && t[j] > x) {
|
||||
t[j + 1] = t[j];
|
||||
j--;
|
||||
}
|
||||
t[j + 1] = x;
|
||||
}
|
||||
}
|
||||
|
||||
void selection_sort(int t[], int n) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
int min = t[i];
|
||||
int min_i = i;
|
||||
for (int j = i; j < n; j++) {
|
||||
if (t[j] < min) {
|
||||
min = t[j];
|
||||
min_i = j;
|
||||
}
|
||||
}
|
||||
t[min_i] = t[i];
|
||||
t[i] = min;
|
||||
}
|
||||
}
|
||||
|
||||
void cocktail_sort(int t[], int n) {
|
||||
for (int i = 0; i < n / 2; i++) {
|
||||
for (int j = i; j < n - i - 1; j++) {
|
||||
if (t[j] > t[j + 1]) {
|
||||
int tmp = t[j + 1];
|
||||
t[j + 1] = t[j];
|
||||
t[j] = tmp;
|
||||
}
|
||||
}
|
||||
for (int j = n - i - 2; j >= i; j--) {
|
||||
if (t[j] > t[j + 1]) {
|
||||
int tmp = t[j + 1];
|
||||
t[j + 1] = t[j];
|
||||
t[j] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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[6];
|
||||
memcpy(t1, t, n * sizeof(int));
|
||||
insertion_sort(t1, n);
|
||||
assert(memcmp(t1, sorted, n * sizeof(int)) == 0);
|
||||
|
||||
memcpy(t1, t, n * sizeof(int));
|
||||
selection_sort(t1, n);
|
||||
assert(memcmp(t1, sorted, n * sizeof(int)) == 0);
|
||||
|
||||
memcpy(t1, t, n * sizeof(int));
|
||||
cocktail_sort(t1, n);
|
||||
printt(t1, n);
|
||||
assert(memcmp(t1, sorted, n * sizeof(int)) == 0);
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user