6-16 编程练习题答案
2014-06-21 13:38
399 查看
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] numbers = new int[100000]; for(int i = 0; i < 100000; i++) numbers[i] = (int)(Math.random() * 100000); int key = (int)(Math.random() * 100000); long startTime = System.currentTimeMillis(); System.out.println(linearSearch(numbers, key)); long endTime = System.currentTimeMillis(); long executionTime = endTime - startTime; System.out.println("The linearSearch has spent " + executionTime + " milliseconds"); Arrays.sort(numbers); startTime = System.currentTimeMillis(); System.out.println(binarySearch(numbers, key)); endTime = System.currentTimeMillis(); executionTime = endTime - startTime; System.out.println("The linearSearch has spent " + executionTime + " milliseconds"); } public static int linearSearch(int[] list, int key) { for(int i = 0; i < list.length; i++) if(key == list[i]) return i; return -1; } public static int binarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; while(high >= low) { int mid = (low + high) / 2; if(key < list[mid]) high = mid - 1; else if(key == list[mid]) return mid; else low = mid + 1; } return -low - 1; } }
相关文章推荐
- python核心编程第六章练习题答案 (2,3,5,6,7,8,12,13,14,16)
- Java语言程序设计基础篇原书第十版第二章编程练习题答案
- Java语言程序设计基础篇原书第十版第六章编程练习题答案
- 6-10 编程练习题答案
- 7-3 编程练习题答案
- Java语言程序设计基础篇原书第十版第四章编程练习题答案
- c语言编程练习题及答案
- 7-4 编程练习题答案
- Java程序语言设计基础篇原书第十版第三章答案编程练习题
- 7-5 编程练习题答案
- C#网络应用编程基础练习题与答案(1)
- 7-6 编程练习题答案
- Java语言程序设计基础篇第十版第一章编程练习题答案
- 编程练习题 没答案版
- 7-7 编程练习题答案
- 7-8 编程练习题答案
- 【NEUQ QJ】编程练习题1009 答案
- 6-11 编程练习题答案
- 6-5 编程练习题答案
- 6-13 编程练习题答案