diff --git a/Programmation/Code/Refactor/tri.c b/Programmation/Code/Refactor/tri.c new file mode 100644 index 0000000000000000000000000000000000000000..f1ad0d8961376ca2d2bd1428ef105938e48da6c2 --- /dev/null +++ b/Programmation/Code/Refactor/tri.c @@ -0,0 +1,71 @@ +#include <stdio.h> +#include <stdlib.h> +#include <time.h> +#include <stdbool.h> + +#define SIZE 10 + +// initialise aléatoirement le tableau +// avec des valeurs entre 0 et 1 +void init(double tab[]){ + for (int i = 0; i < SIZE; ++i) { + tab[i] = rand() / (double)RAND_MAX; + } +} + +// retourne l'indice de l'élément minimum à +// partir de l'indice lbound +int indmin(double tab[], int lbound){ + double min = tab[lbound]; + int ind_min = lbound; + for (int j = lbound + 1; j < SIZE; ++j) { + if (min > tab[j]) { + ind_min = j; + min = tab[j]; + } + } + return ind_min; +} + +// trie le tableau par ordre croissant +// avec le tri par selection +void sort(double tab[]){ + for (int i = 0; i < SIZE - 1; ++i) { + int ind_min = indmin(tab, i); + // placer le minimum + double tmp = tab[i]; + tab[i] = tab[ind_min]; + tab[ind_min] = tmp; + } +} + +// affiche le tableau +void print(double tab[]){ + for (int i = 0; i < SIZE; ++i) { + printf("%f ", tab[i]); + } + printf("\n"); +} + +// retourne vrai si le tableau est trié +// faux sinon +bool issorted(double tab[]){ + for (int i = 0; i < SIZE - 1; ++i) { + if (tab[i] > tab[i + 1]) { + return false; + } + } + return true; +} + +int main() { + srand(time(NULL)); + double tab[SIZE]; + + init(tab); + sort(tab); + print(tab); + + if(!issorted(tab)) return EXIT_FAILURE; + return EXIT_SUCCESS; +}