http://ideone.com/RT84T6Recherche binaire - Contrôle égalité différée
while (first <= last) {
// Assert: Array is sorted and first <= last
//Initialization:target is within (extremes inclusive) the range of first and last. IE First<=x<=Last
mid = (first+last)/2;
//Maintenance: Increasing first to mid+1 if x>mid or decrease last to min-1 if x<mid.
if (target < arr[mid]) last = mid-1;
else first = mid+1;
}
//Termination: target is not within the array.
return -1;
if ((first <= target) && (arr[first]==target)) return 1;
else return -1;
}
Je reçois une sortie de -1 à chaque fois que je lance ma recherche binaire (détection différée de la version d'égalité).
Je n'arrive pas à déterminer où il en résulte un -1.
mettre 'if (arr [mid] == target) retourne 1;' dans while-loop. – BLUEPIXY
Il y a quelques problèmes ici. D'abord, considérons ce qui se passe si 'arr [mid]' est égal à 'target'. Dans ce cas, vous définissez «first» à «mid + 1», c'est-à-dire que vous déplacez «first» après l'emplacement de «target». Deuxièmement, à la fin, vous comparez 'first', qui est un indice de tableau, à' target', qui est une valeur de tableau. Cela ne marche évidemment pas. –
bleu, je veux qu'il ait strictement 2 comparaisons dans la boucle while. @TomKarzes Ah, merci! Il devient tard où je suis et mon cerveau perd sa capacité à raisonner: P J'ai fait ces changements, j'espère que ça marche! while (! (Premier <= dernier) && (arr [mi] = cible)) if ((premier == dernier) && (arr [premier] == cible)) return 1; \t sinon retour -1; –