用上周日的时间从头开始看《算法4》第一章,接触的第一个算法二分查找法。这个算法之前在大三学数据结构的时候有接触到,代码如下:
package algorithms;
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 {
public static int rank(int key,int[] arr){
int a = 0;
int b = arr.length-1;
int middle;
while(a<=b){
middle = (a+b)/2;
if(key<arr[middle]){
b = middle-1;
}else if(key>arr[middle]){
a = middle+1;
}else{
return middle;
}
}
return -1;
}
public static void main(String[] args) {
@SuppressWarnings("deprecation")
int[] whitelist = In.readInts(args[0]);
Arrays.sort(whitelist);
while(!StdIn.isEmpty()) {
int key = StdIn.readInt();
if(rank(key, whitelist) < 0)
StdOut.println(key);
}
}
}