Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Optimizing Code in Java

Cursus bekijken

Oefeninstructies

  • 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.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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;
    }
}
Code bewerken en uitvoeren