import java.util.*;
import java.io.*;
/* 二分查找方法 */
public class BinarySearch
{
public static int rank(int [] list,int key)
{
int lo=0;
int hi=list.length-1;
while(lo<=hi)
{
int mid=(lo+hi)/2;
if(key<list[mid]) hi=mid-1;
else if (key>list[mid]) lo=mid+1;
else return mid;
}
return -1;
}
//////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws Exception
{
/* read the .txt file using the command line. */
File file =new File(args[0]);
Scanner input=new Scanner(file);
/* get the data by using ArrayList */
ArrayList list=new ArrayList();
while(input.hasNext())
{
int temp=input.nextInt();
list.add(temp);
}
/* 把动态数组转化为数组 */
int size=list.size();
System.out.println("There are "+size+" integers in the whitelist.");
System.out.println("***********************");
int[] Whitelist=new int[size];
for(int i=0;i<size;i++)
Whitelist[i]=(int)list.get(i);
/* for(int i=0;i<size;i++)
System.out.println(Whitelist[i]); //print the data
System.out.println("***********************");
*/
/*对白名单进行升序排列 */
Arrays.sort(Whitelist);
/* for(int i=0;i<size;i++)
System.out.println(Whitelist[i]); //print the sorted data
System.out.println("***********************");
*/
//////////////////////////////////////////////////////////
/* Compare the data with thw whitelist,and then print the data that is not in the whitelist */
Scanner scanner=new Scanner(System.in);
int n=0;
while(scanner.hasNext())
{
int key=scanner.nextInt();
if(rank(Whitelist,key)<0)
{
System.out.println(key);
n=n+1;
}
}
System.out.println("There are"+ n +" integers not in the whitelist.");
}
}
利用BinarySearch方法,可以验证某个数据是否在给定的白名单中。为了进行实验,从本书的网站上下载了两个数据文件largeW.txt和largeT.txt,其中前者为100万个数据,后者1000万个数据。将前者作为白名单,将后者的不在白名单的数据查找并打印出来。
首先是读取文件数据,这里利用了Java.io.File获取文件属性,再利用java.util.Scanner读取文件中的数据,由于数据的多少提前不知道的,因此利用Arraylist作为动态数组进行数据存储,然后获取数组大小后再将其转化为数组,从而利用Array.sort函数方法排序,生成按升序排列的白名单。
对于largeT.txt文件的读取,采用输入重定向方式,每读入一个数据就在白名单中进行搜索,如果白名单中搜索不到就将其打印出来。
最后可以通过输出重定向将搜索结果输出到一个名为search.txt的文件中。
Win7下用命令行运行,运行时间在10s~15s之间。