1.1.38二分查找与暴力查找。根据1.1.10.4节给出的暴力查找法编写一个程序BruteForceSearch,在你的计算机上比较它和BinarySearch处理largeW.txt和largeT.txt所需的时间。
解:
暴力查找约用时:2371秒
二分查找约用时: 17秒
//暴力查找代码
import java.util.Date;
public class BruteForceSearch
{
public static int rank(int key,int[] a)
{
for (int i=0;i<a.length;i++)
if (a[i]==key) return i;
return -1;
}//end rank
public static void main(String[] args)
{
int[] whitelist=In.readInts(args[0]);
int postion;
Date timeStart=new Date();
while (!StdIn.isEmpty())
{
int key=StdIn.readInt();
postion=rank(key,whitelist);
}
Date timeEnd=new Date();
StdOut.printf("BruteForceSearch used time:");
StdOut.println(timeEnd.getTime()-timeStart.getTime());
}
}
//二分查找代码
import java.util.Date;
import java.util.Arrays;
public class BinarySearch
{
public static int rank(int key,int[]a)
{
int lo=0;
int hi=a.length-1;
while (lo<=hi)
{
int mid=lo+(hi-lo)/2;
if (key<a[mid]) hi=mid-1;
else if(key>a[mid]) lo=mid+1;
else return mid;
}
return -1;
}
public static void main(String[] args)
{
int[] whitelist=In.readInts(args[0]);
int postion;
Date timeStart=new Date();
Arrays.sort(whitelist);
while (!StdIn.isEmpty())
{
int key=StdIn.readInt();
postion= rank(key,whitelist);
}
Date timeEnd=new Date();
StdOut.printf("BinarySearch used time:");
StdOut.println(timeEnd.getTime()-timeStart.getTime());
}
}
原文地址:https://www.cnblogs.com/longjin2018/p/9848760.html