第七章第十六题(执行时间)(execution time)
-
7.16(执行时间)编写程序,随机产生一个包含100000个整数的数组和一个关键字。估算调用程序清单7-6中的linearsSearch方法的执行时间。对该数组进行排序,然后估算调用程序清单7-7中的binarySearch方法的执行时间。可以使用下面的代码模板获取执行时间:
long startTime = System.nanoTime();
perform the task;
long endTime = System.nanoTime();
long executingTimr = endTime - startTime;
7.16(execution time)Write a program, randomly generated an array containing 100000 integers and a keyword. Estimate the execution time of the linearsearch method in listing 7-6 of the caller. Sort the array and then estimate the execution time of the binarysearch method in listing 7-7 of the caller. You can use the following code template to get the execution time:
long startTime = System.nanoTime ();
perform the task;
long endTime = System.nanoTime ();
long executingTimr = endTime - startTime; -
参考代码:
package chapter07; public class Code_16 { public static void main(String[] args){ int[] million = createRandomArray(); int kk = (int)(Math.random()*100000); long startTime = System.nanoTime(); linearSearch(kk,million); long endTime = System.nanoTime(); long timel = endTime-startTime; sort(million); startTime = System.nanoTime(); binarySearch(kk,million); endTime = System.nanoTime(); long timeb = endTime-startTime; System.out.println("The time of linear search is "+timel+", and the time of binary search is "+timeb); } public static int[] createRandomArray(){ int[] nums = new int[100000]; for(int i=0;i<100000;i++) nums[i]=(int)(100000*Math.random()); return nums; } public static int linearSearch(int key,int[] num){ int jb=-1; for(int i=0;i<num.length;i++){ if(num[i]==key){ jb=i; break; } } return jb; } public static void sort(int[] num){ for(int i=num.length-1;i>=2;i--){ for(int j=0;j<i;j++){ if(num[j]>num[j+1]){ int tmp = num[j]; num[j] = num[j+1]; num[j+1]=tmp; } } } } public static int binarySearch(int key,int[] num){ int jb=-1; int high=num.length-1; int low=0; while(high>=low){ int mid=(high+low)/2; if(num[mid]==key) jb=mid; else if(num[mid]<key) low=mid+1; else high=mid-1; } return jb; } }
-
结果显示:
The time of linear search is 1114700, and the time of binary search is 21100 Process finished with exit code 0