Travaux dirigs 4 Les tableaux B Shishedjiev Informatique
Travaux dirigés 4 Les tableaux B. Shishedjiev - Informatique II 1
L’élément maximal d’un tableau et sa place int maxel (a[], n, max) i, place max == -1 e 30 a[0] max i=1, place=0 i=0, place =-1 i<n non oui a[i]<0 && a[i]>max non oui max=a[i] place=i i+=1 return place 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 = -1 e-30; for (i=0; i<n; i++) if (a[i] <0 && a[i] > *max){ *max = a[i]; place = i; } return place; } fin B. Shishedjiev - Informatique II 2
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 11 12 13 14 21 22 23 24 31 32 33 34 41 42 43 44 float moyenne 2(float a[][MAXCOL], int m){ int i, j; float s = 0; int compt = 0; for (i=0; i<m; i++) for (j=i+1; j<m; j++) for (j=0; j<m; j++) if (a[i][j] > 0){ if (i<j && a[i][j] > 0){ s+=a[i][j]; compt++; } } if (compt) return s/compt; else return 0; B. Shishedjiev - Informatique II return s; } 3
Tri par sélection 5 3 9 2 6 void trisel(a[], n) k, pl, max k=n non k>1 oui pl=maxel(a, k, max) pl k-1 non oui echange(a[pl]¸, a[k-1] k-=1 fin B. Shishedjiev - Informatique II 4
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 5
Tri par insertion 5 3 9 2 6 piv 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 } } B. Shishedjiev - Informatique II 6
- Slides: 6