HW6.16

时间:2024-12-18 22:04:26

HW6.16

 import java.util.Arrays;

 public class Solution
 {
     public static void main(String[] args)
     {
         int[] array1 = new int[10000];
         int[] array2 = new int[10000];

         for(int i = 0; i < 10000; i++)
         {
             array1[i] = (int)(Math.random() * 100);
             array2[i] = (int)(Math.random() * 100);
         }

         int sign1 = (int)(Math.random() * 100);
         int sign2 = (int)(Math.random() * 100);

         System.out.println("Array1 run time: " + linearRunTime(array1, sign1));
         System.out.println("Array2 run time: " + binaryRunTime(array2, sign2));
     }

     public static long linearRunTime(int[] array, int number)
     {
         long startTime = System.currentTimeMillis();
         linearSearch(array, number);
         long endTime = System.currentTimeMillis();
         long executionTime = endTime - startTime;
         return executionTime;
     }

     public static long binaryRunTime(int[] array, int number)
     {
         Arrays.sort(array);
         long startTime = System.currentTimeMillis();
         binarySearch(array, number);
         long endTime = System.currentTimeMillis();
         long executionTime = endTime - startTime;
         return executionTime;
     }

     public static void linearSearch(int[] array, int number)
     {
         for(int i = 0; i < array.length; i++)
             if(number == array[i])
                 return;
     }

     public static void binarySearch(int[] array, int number)
     { binarySearch(array, number, 0, array.length - 1); }

     public static void binarySearch(int[] array, int number, int low, int high)
     {
         if(low < high)
             return;
         int mid = (low + high) / 2;
         if(number < array[mid])
             binarySearch(array, number, low, mid);
         else if(number > array[mid])
             binarySearch(array, number, mid + 1, high);
         else if(number == array[mid])
             return;
     }
 }

相关文章