首页 > 代码库 > HW6.16

HW6.16

技术分享

 

 1 import java.util.Arrays; 2  3 public class Solution 4 { 5     public static void main(String[] args) 6     { 7         int[] array1 = new int[10000]; 8         int[] array2 = new int[10000]; 9 10         for(int i = 0; i < 10000; i++)11         {12             array1[i] = (int)(Math.random() * 100);13             array2[i] = (int)(Math.random() * 100);14         }15 16         int sign1 = (int)(Math.random() * 100);17         int sign2 = (int)(Math.random() * 100);18 19         System.out.println("Array1 run time: " + linearRunTime(array1, sign1));20         System.out.println("Array2 run time: " + binaryRunTime(array2, sign2));21     }22 23     public static long linearRunTime(int[] array, int number)24     {25         long startTime = System.currentTimeMillis();26         linearSearch(array, number);27         long endTime = System.currentTimeMillis();28         long executionTime = endTime - startTime;29         return executionTime;30     }31 32     public static long binaryRunTime(int[] array, int number)33     {34         Arrays.sort(array);35         long startTime = System.currentTimeMillis();36         binarySearch(array, number);37         long endTime = System.currentTimeMillis();38         long executionTime = endTime - startTime;39         return executionTime;40     }41 42     public static void linearSearch(int[] array, int number)43     {44         for(int i = 0; i < array.length; i++)45             if(number == array[i])46                 return;47     }48 49     public static void binarySearch(int[] array, int number)50     { binarySearch(array, number, 0, array.length - 1); }51 52     public static void binarySearch(int[] array, int number, int low, int high)53     {54         if(low < high)55             return;56         int mid = (low + high) / 2;57         if(number < array[mid])58             binarySearch(array, number, low, mid);59         else if(number > array[mid])60             binarySearch(array, number, mid + 1, high);61         else if(number == array[mid])62             return;63     }64 }

 

HW6.16