zoukankan      html  css  js  c++  java
  • 执行时间 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 }
  • 相关阅读:
    Python开发【Part 2】:初识Python
    Python开发
    python-软件开发目录规范
    python-常用模块-re正则
    python-常用函数模块学习-logging模块
    python-常用函数模块学习-subprocess
    python-常用函数模块hashlib加密
    python-常用函数模块学习
    python-函数-内置方法
    python-函数
  • 原文地址:https://www.cnblogs.com/cherrydream/p/10174125.html
Copyright © 2011-2022 走看看