执行时间 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 }

 

转载于:https://www.cnblogs.com/cherrydream/p/10174125.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值