Java言語実装二分法
二分法は簡単で効率的で広く応用されている検索方法である.
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);
}
}
}