要求:程序接受一个白名单文件(一列整数)作为参数,过滤名单中存在的条目,将其余条目打印

1.寻常实现(利用书中管道和重定向接收输入)

  1. public class BinarySearch{
  2. public static int rank(int key, int[] a){
  3. int low = 0;
  4. int high = a.length - 1;
  5. while(low <= high){
  6. int mid = (low + high)/2;
  7. if(a[mid] < key) low = mid + 1;
  8. else if(a[mid] > key) high = mid - 1;
  9. else return a[mid];
  10. }
  11. return -1;//无键值,返回-1
  12. }
  13. pubilc static void main(String[] args){
  14. int[] whitelist = In.readInts(args[0]);
  15. Arrays.sort(whitelist);
  16. while(!StdIn.isEmpty()){
  17. int key = StdIn.readInt();
  18. if(rank(key, whitelist) < 0)
  19. StdOut.println(key);
  20. }
  21. }

要点
1.high = a.length - 1;
2.low <= high: 当a[] = {1,3,5},查找5时,当条件只是low < high,无法找到5;
3.mid ± 1: 若没有±1操作,当无键值时,无法有low <= high跳出循环


2.递归实现

  1. public int rank(int low, int high, int key, int[] a){
  2. int mid = (low + high)/2;
  3. while(low <= high){
  4. if(a[mid] == key) return a[mid];
  5. else if(a[mid] < key) return rank(mid+1, high, key, a);
  6. else return rank(low, mid-1, key, a);
  7. }
  8. return -1;
  9. }

3.运行注意

在存放java文件的文件夹中运行PowerShell,输入cmd命令后执行java BinarySearch tinyW.txt < tinyT.txt,此时tinyW.txt即参数args[0],tinyT.txt中的数由StdIn读取