1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #include <stdio.h>
#include <stdlib.h>
// Prototypage
void AfficheTableau(int [], int);
void TriABulle(int [], int, char);
int cmp(int, int, char);
int main()
{
int tableau[]={12,1,3,0,17,45,32,9};
AfficheTableau(tableau, 8);// ici le tableau non trié s'affiche
TriABulle(tableau, 8, '<');// puis tri dans l'ordre croissant
AfficheTableau(tableau, 8);// Et enfin, le tableau trié s'affiche
TriABulle(tableau, 8, '>');// puis tri dans l'ordre décroissant
AfficheTableau(tableau, 8);// Et enfin, le tableau trié s'affiche
return 0;
}
void AfficheTableau(int t[], int s)
{
int i;
for (i=0; i<s; i++)
printf("%d ", t[i]);
printf("\n");
}
void TriABulle (int t[], int s, char c)
{
int bad;
int i;
int tmp;
// Traitement de base
do {
bad=0;
// Traitement du tableau
for(i=1; i < s; i++)
{
// Si les 2 éléments sont mal placés
if (cmp(t[i-1], t[i], c) > 0)
{
// Intervertion
tmp=t[i-1];
t[i-1]=t[i];
t[i]=tmp;
// Le tableau n'est pas trié, faudra recommencer le tout
bad=1;
}
}
} while (bad);
}
int cmp(int x, int y, char c)
{
if ((x < y && c == '<') || (x > y && c == '>')) return -1;
if ((x > y && c == '<') || (x < y && c == '>')) return 1;
return 0;
} |
Partager