首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。