Comparer les performances des algorithmes de recherche
En tant que développeur·se logiciel·le dans une entreprise d’e‑commerce, vous évaluez différentes méthodes de recherche pour améliorer la recherche de produits. Jusqu’ici, le mécanisme utilisé par l’entreprise était très lent, mais vous avez déjà réussi à supprimer ce délai. Votre tâche consiste maintenant à comparer votre nouvelle méthode de recherche avec l’ancienne, afin de démontrer qu’elle est plus efficace pour la recherche dans votre catalogue.
Cet exercice fait partie du cours
Optimiser son code en Java
Instructions
- Trouvez l’élément cible à l’aide de la nouvelle méthode de recherche,
linearSearch(). - Puis, trouvez l’élément cible à l’aide de l’ancienne méthode,
linearSearchWithDelay(). - Calculez la différence de performances relatives entre les deux méthodes de recherche.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
public class SearchPerformanceTest {
public static void main(String[] args) {
int[] array = new int[10000];
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
int target = array[7500]; // Target value to search for
long startRegular = System.nanoTime();
// Do a search using the new search method
boolean foundRegular = ____(array, target);
long endRegular = System.nanoTime();
long startDelay = System.nanoTime();
// Do a search using the old search method
boolean foundDelay = ____(array, target);
long endDelay = System.nanoTime();
// Calculate the ratio between the old and new methods
double ratio = (double)(endDelay - startDelay) / (____ - ____);
System.out.println("Linear search with delay is " + ratio +
" times slower than regular linear search");
}
private static boolean linearSearch(int[] data, int target) {
for (int i = 0; i < data.length; i++) {
if (data[i] == target) return true;
}
return false;
}
private static boolean linearSearchWithDelay(int[] data, int target) {
for (int i = 0; i < data.length; i++) {
try {
Thread.sleep(0, 1000); // 1000 nanoseconds delay
} catch (InterruptedException e) {
e.printStackTrace();
}
if (data[i] == target) return true;
}
return false;
}
}