Vous êtes sur la page 1sur 2

MMS - Algorithmique

Algorithme du tri fusion


Le tri fusion utilise le paradigme diviser pour rgner : On divise le tableau T trier en deux tableaux qui ont peu prs le mme nombre d'lments : T1 et T2 ; On rgne : on trie rcursivement les deux tableaux T1 et T2 l'aide du tri fusion ; On combine : on fusionne les deux squences tries pour produire le tableau tri.

1) Algorithme crit pour les tableaux


Fonction TriFusion(T: Tableau): Tableau tri; n := taille de T; Si n = 1 retourne T Sinon retourne Fusion(TriFusion(T[1 .... E[n/2]], TriFusion(T[E[n/2]+1 .... n])); FinSi FinFonction Fonction Fusion(A: Tableau tri; B: Tableau tri): Tableau tri; tailleA := taille de A; tailleB := taille de B; tailleTfusion := taille de A + taille de B; Tfusion := nouveau tableau de taille tailleTfusion; indiceA := 1; indiceB := 1; indiceTfusion := 1; Pour indiceTfusion := 1 tailleTfusion faire Si (indiceA > tailleA) alors Tfusion[indiceTFusion] := B[indiceB]; indiceB := indiceB + 1; Sinon si (indiceB > tailleB) alors Tfusion[indiceTFusion] := A[indiceA]; indiceA := indiceA + 1; Sinon si A[indiceA] B[indiceB] alors Tfusion[indiceTFusion] := A[indiceA]; indiceA := indiceA + 1; Sinon Tfusion[indiceTFusion] := B[indiceB]; indiceB := indiceB + 1; FinSi FinPour Retourner Tfusion; FinFonction

MMS - Algorithmique
Autre version de Fusion : Fonction Fusion(A: Tableau tri; B: Tableau tri): Tableau tri; tailleTfusion := taille de A + taille de B; Commentaire : on met juste + pour viter de lire en dehors des tableaux A := A auquel on a ajout une case en fin de tableau qui contient + ; B := B auquel on a ajout une case en fin de tableau qui contient + ; Tfusion := nouveau tableau de taille tailleTfusion; indiceA := 1; indiceB := 1; Pour indiceTfusion := 1 tailleTfusion faire Si A[indiceA] B[indiceB] alors Tfusion[indiceTFusion] := A[indiceA]; indiceA := indiceA + 1; Sinon Tfusion[indiceTFusion] := B[indiceB]; indiceB := indiceB + 1; FinSi FinPour Retourner Tfusion; FinFonction

2) Algorithme crit pour les listes


Fonction TriFusion(L: Liste): Liste trie; Si L = [] ou L = [a] Retourner L Sinon L1, L2 := Diviser(L); Retourner Fusion(TriFusion(L1), TriFusion(L2); FinFonction Fonction Diviser(L: Liste): Liste Liste;
(cette fonction est un peu stupide quand mme...)

Si L = [] Retourner [], [] Sinon L s'crit a::L' Si L' = [] Retourner [a], [] Sinon L' s'crit b::L'' L1, L2 := Diviser(L) Retourner a::L1, b::L2 FinSi FinSi FinFonction

Fonction Fusion(A, B: Listes tries): Liste trie; Si A = [] alors Retourner B Sinon si B = [] alors Retourner A Sinon A s'crit a::A' B s'crit b::B' et alors Si a < b alors Retourner a::Fusion(A', B); Sinon Retourner b::Fusion(A, B'); FinSi FinSi FinFonction

Vous aimerez peut-être aussi