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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
swap_i (int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
/* http://en.wikipedia.org/wiki/Bubble_sort */
void tri_bulle (int *tab, int n)
{
int a = clock ();
int swapped;
unsigned long count = 0;
printf ("tri en cours ...");
fflush (stdout);
do
{
int i;
swapped = 0;
n--;
for (i = 0; i < n; i++)
{
if (tab[i] > tab[i + 1])
{
swap_i (tab + i, tab + i + 1);
swapped = 1;
count++;
}
}
}
while (swapped);
printf ("\rtri bulle : %ld (%lu swap%s)\n", clock () - a, count,
count > 1 ? "s" : "");
}
void inversion (int tab[], int n)
{
int i;
for (i = 0; i < n - 1; i++)
{
swap_i (tab + i, tab + i + 1);
}
}
void init (int tab[], int n)
{
int i;
for (i = 0; i < n; i++)
{
tab[i] = (rand () / (double) RAND_MAX) * 100;
}
}
void aff (int const tab[], int n)
{
int i;
for (i = 0; i < n; i++)
{
printf ("%4d", tab[i]);
}
}
int main (void)
{
#define N 50000
static int tab[N];
srand (time (NULL));
rand ();
init (tab, N);
aff (tab, 20);
tri_bulle (tab, N);
aff (tab, 20);
inversion (tab, N);
aff (tab, 20);
tri_bulle (tab, N);
aff (tab, 20);
tri_bulle (tab, N);
aff (tab, 20);
return 0;
} |
Partager