< Algorithmique impérative

Problématique

Donner un algorithme qui, étant donné un tableau d'entiers, trouve le plus petit écart entre deux éléments.

Exemples :

  • [1|10|4|6] : 6-4 = 2
  • [1|10] : 10-1 = 9
  • [5|5] : 5-5 = 0

Donner un algorithme qui, étant donné un tableau d'entiers, trouve le plus grand écart entre deux éléments.

Solution

Une implémentation testable en Pascal

 1program ecarts;
 2
 3const
 4	DEB = 0;
 5	FIN = 10;
 6
 7type
 8	T_tabint = array [DEB..FIN] of integer;
 9
10procedure afficher(var t : T_tabint);
11(* procédure qui affiche le tableau passé en paramètre *)
12(* sur une ligne et sous la forme [a|b|c|d...|l|m] *)
13
14var
15	i : integer; (* variable de boucle *)
16begin
17	write('[');
18	for i := DEB to FIN-1 do write(t[i],'|');
19	write (t[FIN],']');
20end;
21
22procedure remplir(var t : T_tabint);
23(* procédure qui remplit le tableau passé en paramètre *)
24(* avec des nombres aléatoires pris entre 0 et 99 *)
25
26var
27	i : integer; (* variable de boucle *)
28begin
29	for i := DEB to FIN do t[i] := random(99);
30end;
31
32procedure RechercheEcartMin(t : T_tabint);
33var
34	i,j : integer; (* variables de boucle *)
35	ind1,ind2 : integer; (* indices *)
36	ecart_min_trouve : integer;
37	
38begin
39	ecart_min_trouve := MAXINT;
40	for i := DEB to FIN-2 do begin
41		for j:= i+1 to FIN do begin
42			if (abs(t[i]-t[j]) <= ecart_min_trouve) then begin
43				ecart_min_trouve := abs(t[i]-t[j]);
44				ind1 := i;
45				ind2 := j;
46			end;			
47		end;
48	end;
49	writeln('écart minimal trouvé : ',t[ind1],' - ',t[ind2],' = ',ecart_min_trouve)
50end;
51
52procedure RechercheEcartMax(t : T_tabint);
53var
54	i : integer; (* variable de boucle *)
55	min,max : integer; (* indices du plus petit élément et du plus grand élément *)
56
57begin
58	min := DEB;
59	max := DEB;
60	for i:= DEB to FIN do begin
61		if t[i] < t[min] then min := i;
62		if t[i] > t[max] then max := i;
63	end;
64	writeln('écart maximal trouvé : ',t[max],' - ',t[min],' = ',t[max]-t[min])
65end;
66
67var
68	tab : T_tabint;
69
70begin
71	remplir(tab);
72	afficher(tab);
73	writeln(' <- tableau donné');
74	RechercheEcartMin(tab);
75	RechercheEcartMax(tab);	
76end.

Exemple de résultat produit par le programme :

[54|58|70|83|59|84] <- tableau donné
écart minimal trouvé : 83 - 84 = 1
écart maximal trouvé : 84 - 54 = 30
Cet article est issu de Wikibooks. Le texte est sous licence Creative Commons - Attribution - Partage dans les Mêmes. Des conditions supplémentaires peuvent s'appliquer aux fichiers multimédias.