开始使用免费开始使用

比较搜索算法的性能

作为一家电商公司的软件开发人员,您正评估不同的搜索方式以改进商品搜索功能。之前公司的搜索机制非常缓慢,但您已经设法去除了那部分延迟。现在您的任务是将新的搜索方法与旧方法进行比较,以证明它在目录搜索功能中更高效。

本练习是课程的一部分

Java 代码优化

查看课程

练习说明

  • 使用新的搜索方法 linearSearch() 查找目标元素。
  • 然后使用旧的搜索方法 linearSearchWithDelay() 查找目标元素。
  • 计算两种搜索方法的相对性能差异。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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;
    }
}
编辑并运行代码