Travaux dirigés 4
description
Transcript of Travaux dirigés 4
B.Shishedjiev - Informatique II 1
Travaux dirigés 4
Les tableaux
B.Shishedjiev - Informatique II 2
L’élément maximal d’un tableau et sa place
i,placeint maxel (a[],n,max)
max = a[0]i=1, place=0
a[i]>max
max=a[i]place=i
non
oui
i+=1
return place
fin
i<n
non
oui
max = -1e30i=0,place =-1
a[i]<0 &&
a[i]>max
int maxel( float a[], int n, float *max) {
int i,place = 0; *max = a[0]; for (i=1; i<n;i++)
if (a[i] > *max) { *max = a[i]; place =
i; }return place;
}
int maxel( float a[], int n, float *max) {
int i,place = -1; *max = -1e-30; for (i=0; i<n;i++)
if (a[i] <0 && a[i] > *max){ *max = a[i]; place =
i; }return place;
}
B.Shishedjiev - Informatique II 3
La moyenne Faire une fonction qui calcule la moyenne des éléments positifs qui se
trouvent au dessus du diagonale principal d'une matrice avec M lignes et M colonnes
float moyenne2(float a[][MAXCOL], int m){ int i,j; float s = 0; int compt = 0; for (i=0; i<m;i++) for (j=0; j<m; j++)
if (i<j && a[i][j] > 0){ s+=a[i][j]; compt++;
} if (compt) return s/compt; else return 0; return s;}
for (i=0; i<m;i++) for (j=i+1; j<m; j++) if (a[i][j] > 0){ s+=a[i][j]; compt++; }
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
B.Shishedjiev - Informatique II 4
Tri par sélection
5 3 9 2 6k,pl,max
void trisel(a[],n)
echange(a[pl]¸,a[k-1]
k=n
k>1
pl=maxel(a,k,max)
plk-1
fin
non
oui
k-=1
non
oui
B.Shishedjiev - Informatique II 5
Tri à la boule
5 3 9 2 6
void triboule(float a[], int n) {int i, ech;do {ech = 0; // pas d<echanges encore for (i =1; i<n; i++)
if (a[i-1] > a[i]){ echange(a+i-1, a+i); ech = 1; //on a eu des echanges
}}while (ech);
}
B.Shishedjiev - Informatique II 6
Tri par insertion
5 3 9 2 6
void triins(float a[], int n) {int i, k;float piv;for (i =1; i<n; i++){ piv = a[i]; //l'element pour inserer for (k =i-1; k>=0 && piv < a[k]; k--) a[k+1] = a[k]; a[k+1]=piv; //insertion}
}
piv