Le tableau est trié : trouve la case de x (indices à partir de 0). La recherche dichotomique regarde la case du milieu a[mid] : si c’est x, trouvé ; si c’est plus petit que x, la réponse est à droite ; si c’est plus grand, à gauche. Écris binary_search(a, n, x) : renvoie l’indice, ou -1 si absent. Ex. 7 dans 1 3 5 7 9 11 renvoie 3.
binary_search({1, 3, 5, 7, 9, 11}, 6, 7)→3binary_search({1, 3, 5, 7, 9, 11}, 6, 4)→-1binary_search({2, 4, 6, 8}, 4, 2)→0int binary_search(int a[], int n, int x)int binary_search(int a[], int n, int x) {
int lo = 0, hi = n - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == x) {
return mid;
} else if (a[mid] < x) {
// ton code ici: le milieu est trop petit, cherche dans la moitié droite
} else {
// ton code ici: le milieu est trop grand, cherche dans la moitié gauche
}
}
return -1;
}
Exécuter teste les exemples. Quand ils sont bons, appuie sur Envoyer.