ComeçarComece de graça

Comparing search algorithm performance

As a software developer at an e-commerce company, you're evaluating different search methods to improve product search functionality. Until now, the search mechanism the company was using was very slow, but you managed to remove that delay already. Your task now is to compare your new search method with the old one, to prove it is more efficient for your catalog search feature.

Este exercício faz parte do curso

Optimizing Code in Java

Ver curso

Instruções do exercício

  • Find the target element using the new search method, linearSearch().
  • Then, find the target element using the old search method, linearSearchWithDelay().
  • Calculate the relative performance difference of the search methods.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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;
    }
}
Editar e executar o código