您的位置:首页 > 编程语言

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: