执行时间 Exercise07_16

 1 import java.util.Arrays;
 2 import java.util.Scanner;
 3 /**
 4  * @author 冰樱梦
 5  * 时间:2018年下半年
 6  * 题目:执行时间
 7  *
 8  */
 9 public class Exercise07_16 {
10     public static void main(String[] args){
11         int[] list=new int[100000];
12         for(int i=0;i<list.length;i++){
13             list[i]=(int)(Math.random()*100000);
14         }
15         int key=(int) (Math.random()*100000);
16         long startTime=System.nanoTime();
17         System.out.println(LinearSearch(list,key));
18         long endTime=System.nanoTime();
19         long executionTime=endTime-startTime;
20         System.out.println("时间为: "+executionTime);
21         
22         Arrays.sort(list);
23         startTime=System.nanoTime();
24         System.out.println(BinarySearch(list,key));
25         endTime=System.nanoTime();
26         executionTime=endTime-startTime;
27         System.out.println("时间为: "+executionTime);
28         
29     }
30     public static int LinearSearch(int[] list,int key){
31         for(int i=0;i<list.length;i++){
32             if(key==list[i]){
33                 return i;
34             }
35         }
36         return -1;
37     }
38     public static int BinarySearch(int[] list,int key){
39         int low=0;
40         int high=list.length-1;
41         while(high>=low){
42             int mid=(low+high)/2;
43             if(key<list[mid]){
44                 high=mid-1;
45             }
46             else if(key==list[mid]){
47                 return mid;
48             }
49             else low=mid+1;
50         }
51         return -low-1;
52     }
53 }

 

posted @ 2018-12-25 15:18  CHERRYL  阅读(178)  评论(0编辑  收藏  举报