#include #include /* exit */ void printTab(int tab[], int size) { int i; printf("{"); for(i=0;i<=size-1;i=i+1) { if (i==size-1) printf("%d",tab[i]); else printf("%d ",tab[i]); } printf("}"); } void trace(int tab[], int size, int i, int j) { printf("%d ",i); printf("%d ",j); printTab(tab,size); printf("\n"); } void echange(int tab[], int size, int i, int j) { int temp; #if 1 /* Soit on ecrit comme ca les preconditions: */ if (!(i>=0 && i<=size-1)) { printf("Parametre i invalide\n"); exit(1); } if (!(j>=0 && j<=size-1)) { printf("Parametre j invalide\n"); exit(1); } #else /* Soit on ecrit comme ca les preconditions: */ if (i<0 || i>=size) { printf("Parametre i invalide\n"); exit(1); } if (j<0 || j>=size) { printf("Parametre j invalide\n"); exit(1); } #endif temp = tab[i]; tab[i] = tab[j]; tab[j] = temp; } void triBulleRuse(int tab[], int size) { int inversion = 1; /* vrai au depart */ int i,j; int n = size; i=0; while (i<=n-1 && inversion) /* Permet de s'arreter si le tableau */ { /* est deja trie */ inversion = 0; /* faux */ for(j=0; j<=n-1-i-1 ; j=j+1) /* n-1: comme d'habitude */ { /* -i: car les i derniers sont deja tries */ if (tab[j]>tab[j+1]) /* -1: pour le j+1 (afin de ne pas deborder) */ { echange(tab,size,j,j+1); inversion = 1; /* vrai */ } /* trace(tab,size,i,j); */ } i = i + 1; } } void triBulleRuseOptimise(int tab[], int size) { int inversion = 1; /* vrai au depart */ int i; int n = size; while (inversion) /* 1ere boucle "implicite" */ { inversion = 0; /* faux */ for(i=0; i<=n-2; i=i+1) { if (tab[i]>tab[i+1]) { echange(tab,size,i,i+1); inversion = 1; /* vrai */ } /* trace(tab,size,i,n); */ } n = n - 1; } } int main(void) { int tab[5]= {90,67,2,50,23}; int taille = 5; printTab(tab,taille); printf("\n"); triBulleRuse(tab,taille); printTab(tab,taille); printf("\n"); return 0; }