二分法是一个简单,高效,并广泛应用的查找方法
import java.util.arrays;
public class BinarySearch
{
public static int rank(int key, int[] a)
{
//数组必须是有序的
int lo = 0;
int hi = a.length - 1;
while (l0 <= hi)
{
int mid = lo + (lo + hi) / 2;
if (key < a[mid]) hi = mid - 1;
else if (key > a[mid]) lo = mid + 1;
else return mid;
}
return -1;
}
public static void main(String[] args)
{
//自己创建的函数,读取一个Int数组
int[] whiteList = In.readInts(args[0]);
Arrays.sort(whiteList);
//判断输入的int值是否是空
while(!StdIn.isEmpty())
{
int key = StdIn.readInt();
//如果不包含就打印key值
if (rank(key,whiteList)
StdOut.println(key);
}
}
}