利用二分查找法打印白名单中不存在的数据
来源:互联网 发布:谌龙vs陶菲克交手数据 编辑:程序博客网 时间:2024/05/16 15:15
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之间。
0 0
- 利用二分查找法打印白名单中不存在的数据
- 利用二分查找法查找数据
- 处理查找海量数据中不存在的一个
- 《编程珠玑》第二章2.1 二分查找不存在的数
- 二分查找一个不存在的元素,最多需要比较多少次?
- 查找数据表中不存在的ID号
- 查找数据表中不存在的ID号
- 查找数组中不存在的两个数字
- 浅谈数据的查找(二分查找)
- 检索算法 ---利用二分查找进行数据重复次数统计
- 笔记:ResultSet中数据不存在的情况
- 利用折半查找法(二分查找法)查找员工编号并输出员工的相关资料
- 查找有序序列中 重复/不存在 的数算法
- javascript中二分查找法的两种实现方式
- java语言实现二分查找数据法
- 二分查找法,插入相应数据
- C++二分查找法插入数据
- 数组的二分查找法
- Bash下如何批量重命名、复制文件添加前缀
- UGUI文本字体颜色和大小等代码修改
- Python optparser库详解
- Apache POI 第五讲之利用POI 实现数据的批量导出
- Redis源码解析:29事务
- 利用二分查找法打印白名单中不存在的数据
- RUBY NOTES
- linux命令真是有点多,需要在linux平台多摸索一哈
- ext3日志模式---文件系统
- 7_4_O题 Heavy Transportation 题解[POJ 1797](Dijkstra变形)
- 关于命令行下java程序的jar打包与运行
- 修改iar工程,字体变化的解决方法
- There is no result type defined for type 'json' mapped with name 'success'.
- macbook pro keyboard type in symbols