Get startedGet started for free

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.

This exercise is part of the course

Optimizing Code in Java

View Course

Exercise instructions

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

Hands-on interactive exercise

Have a go at this exercise by completing this sample 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;
    }
}
Edit and Run Code