始める無料で始める

検索アルゴリズムのパフォーマンス比較

あなたは e コマース企業のソフトウェア開発者として、商品検索機能を改善するために複数の検索手法を評価しています。これまで使われていた検索方式は非常に遅かったものの、その遅延はすでに取り除きました。次のタスクは、新しい検索方式が旧方式より効率的であることを示すために、両者のパフォーマンスを比較することです。

この演習はコースの一部です

Javaコード最適化

コースを見る

演習の手順

  • 新しい検索メソッド linearSearch() を使って、目的の要素を見つけます。
  • 次に、旧来の検索メソッド linearSearchWithDelay() を使って、目的の要素を見つけます。
  • 2 つの検索メソッドの相対的なパフォーマンス差を計算します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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;
    }
}
コードを編集して実行