Skip to content
Snippets Groups Projects
Verified Commit a3288fbd authored by orestis.malaspin's avatar orestis.malaspin
Browse files

added cours 7

parent 2e695f75
No related branches found
No related tags found
No related merge requests found
--- ---
title: "Tris" title: "Tris et backtracking"
date: "2021-11-12" date: "2021-11-12"
patat: patat:
eval: eval:
...@@ -197,7 +197,7 @@ int partition(int size, int array[size], int first, int last) { ...@@ -197,7 +197,7 @@ int partition(int size, int array[size], int first, int last) {
} }
``` ```
# Tri à bulle (1/N) # Tri à bulle (1/4)
## Algorithme ## Algorithme
...@@ -214,17 +214,86 @@ int partition(int size, int array[size], int first, int last) { ...@@ -214,17 +214,86 @@ int partition(int size, int array[size], int first, int last) {
* Plus besoin de le traiter. * Plus besoin de le traiter.
* A chaque parcours on s'arrête un élément plus tôt. * A chaque parcours on s'arrête un élément plus tôt.
# Tri à bulle (2/N) # Tri à bulle (2/4)
## Exemple ## Exemple
![Tri à bulles d'un tableau d'entiers](figs/tri_bulles.svg) ![Tri à bulles d'un tableau d'entiers](figs/tri_bulles.svg)
# 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;
}
}
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment