view algs4/BinarySearch/BinarySearch.java @ 0:17ee997bf124

Initial commit
author Eris Caffee <discordia@eldalin.com>
date Sat, 16 May 2015 12:02:55 -0500
parents
children
line source
1 import java.util.Arrays;
3 public class BinarySearch {
4 public static int rank( int key, int[] a ) {
5 int lo = 0;
6 int hi = a.length - 1;
7 while ( lo <= hi) {
8 int mid = lo + ( hi - lo ) / 2;
9 if ( key < a[mid] )
10 hi = mid - 1;
11 else if ( key > a[mid] )
12 lo = mid + 1;
13 else
14 return mid;
15 }
16 return -1;
17 }
19 public static void main( String[] args ) {
20 int[] whitelist = In.readInts( args[0] );
22 Arrays.sort( whitelist );
24 while ( ! StdIn.isEmpty() ) {
25 int key = StdIn.readInt();
26 if ( rank( key, whitelist ) >= 0 )
27 StdOut.println( key );
28 }
29 }
31 }