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
| #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#define N 30
/* Fonction de comparaison de 2 entiers, utilisée par qsort */
int comp (const void * a, const void * b)
{
return ( *((int*)a) - *((int*)b) );
}
/* Fonction d'affichage d'un tableau */
void afficheTableau(int t[], int size)
{
int i;
for (i=0; i < size; ++i)
printf("%d ", t[i]);
printf("\n");
}
bool rechercheDichotomique (int tab[], int elem, int indexL, int indexR){
int milieu = (indexR+indexL)/2;
if(elem == tab[milieu])
return true;
else
{
if (elem < tab[milieu]){
rechercheDichotomique(tab,elem, indexL, milieu-1);}
if (elem>tab[milieu]){
rechercheDichotomique(tab,elem, milieu+1, indexR);}
}
return false;
}
int main() {
int tab[N];
int elem1, elem2;
int i;
//generation aleatoire des elements du tableau
srand(time(NULL));
for(i = 0; i < N; ++i) {
tab[i] = rand()%100;
}
//tri du tableau
qsort (tab, N, sizeof(int), comp);
elem1 = tab[N-1];
elem2 = 100;
printf("Le tableau tab: \n");
afficheTableau(tab, N);
printf("Element à rechercher:");
int elem;
scanf("%d", &elem);
int indexR = elem2;
int indexL = elem1;
rechercheDichotomique(tab,elem,indexL,indexR);
return EXIT_SUCCESS;
} |
Partager