diff --git a/slides/cours_7.md b/slides/cours_7.md index 67a8f04aff084ba35b769699639f7671a4a1a14f..0f00fe88c357359e94c228e154ffd22ce1d3b92a 100644 --- a/slides/cours_7.md +++ b/slides/cours_7.md @@ -1,5 +1,5 @@ --- -title: "Tris" +title: "Tris et backtracking" date: "2021-11-12" patat: eval: @@ -197,7 +197,7 @@ int partition(int size, int array[size], int first, int last) { } ``` -# Tri à bulle (1/N) +# Tri à bulle (1/4) ## Algorithme @@ -214,17 +214,86 @@ int partition(int size, int array[size], int first, int last) { * Plus besoin de le traiter. * A chaque parcours on s'arrête un élément plus tôt. -# Tri à bulle (2/N) +# Tri à bulle (2/4) ## Exemple  -# Tri à bulle (3/N) +# Tri à bulle (3/4) -## Exercice: écrire l'algorithme du tri à bulles +## Exercice: écrire l'algorithme (poster le résultat sur matrix) . . . +```C +void bubble_sort(int size, int array[]) { + for i in [size-1, 1] { + sorted = true; + for j in [0, i-1] { + if (array[j] > array[j+1]) { + swap(array[j], array[j+1]); + sorted = false; + } + } + if (sorted) { + return; + } + } +} +``` + +# Tri à bulle (3/4) + +## Quelle est la complexité du tri à bulles? + +. . . + +* Dans le meilleurs des cas: + * Le tableau est déjà trié: $\mathcal{O}(N)$ comparaisons. +* Dans le pire des cas, $N\cdot (N-1)/2\sim\mathcal{O}(N^2)$: +$$ +\sum_{i=1}^{N-1}i\mbox{ comparaison et }3\sum_{i=1}^{N-1}i \mbox{ affectations +(swap)}\Rightarrow \mathcal{O}(N^2). +$$ +* En moyenne, $\mathcal{O}(N^2)$ ($N^2/2$ comparaisons). + +# L'algorithme du PPCM *récursif* (1/2) + +## Rappel de l'algorithme + +```C +// on cherche i*m == j*m (i,j aussi petits que possibles) +int ppcm(int m, int n) { + int mult_m = m, mult_n = n; + while (mult_m != mult_n) { + if (mult_m > mult_n) { + mult_n += n; + } else { + mult_m += m; + } + } + return mult_m; +} +``` + +. . . + +## Écrire l'algorithme *récursif* du PPCM (matrix) + + +# L'algorithme du PPCM *récursif* (1/2) + +```C +int ppcm(int mult_n, int mult_m, int n, int m) { + if (mult_n < mult_m) { + return ppcm(n + mult_n, mult_m, n, m); + } else if (mult_n > mult_m) { + return ppcm(mult_n, m + mult_m, n, m); + } else { + return mult_n; + } +} +```