下麵是我的代碼,其中需要的外部庫InStdOutStdIn我已經導入
import java.util.Arrays;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class BinarySearch {
/**
* This class should not be instantiated.
*/
private BinarySearch() {}
/**
* Returns the index of the specified key in the specified array
* @param a the array of integers,must be sorted in ascending order
* @param key the search key
* @return index of key in array {@code a} if present;{@code -1} otherwise
*/
public static int indexOf(int[] a,int key){
int lo = 0;
int hi = a.length - 1;
while(lo < hi){
//key is in a[li..hi] or not present
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 int rank(int key ,int a[]){
return indexOf(a, key);
}
public static void main(String[] args){
In in =new In(args[0]);
int[] whitelist = in.readAllInts();
Arrays.sort(whitelist);
while(!StdIn.isEmpty()){
int key = StdIn.readInt();
if(BinarySearch.indexOf(whitelist, key)==-1){
StdOut.println(key);
}
}
}
}
測試結果:
*Exception in thread "main" java.lang.IllegalArgumentException: Could not open 8907
at edu.princeton.cs.algs4.In.<init>(In.java:194)
at BinarySearch.main(BinarySearch.java:35)
Caused by: java.net.MalformedURLException: no protocol: 8907
at java.net.URL.<init>(URL.java:585)
at java.net.URL.<init>(URL.java:482)
at java.net.URL.<init>(URL.java:431)
at edu.princeton.cs.algs4.In.<init>(In.java:180)
... 1 more*