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;
}
}
6-16 编程练习题答案
最新推荐文章于 2022-05-14 13:28:38 发布