-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
37 lines (32 loc) · 884 Bytes
/
Copy pathBinarySearch.java
File metadata and controls
37 lines (32 loc) · 884 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
* Sample usage: java BinarySearch tinyW.txt < tinyT.txt
*/
import java.util.Arrays;
public class BinarySearch
{
public static int rank(int key, int[] a)
{ // Array must be sorted.
int lo = 0;
int hi = a.length-1;
while (lo <= hi)
{ // Key is in a[lo..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 void main(String[] args)
{
In in = new In(args[0]);
int[] whitelist = in.readAllInts();
Arrays.sort(whitelist);
while (!StdIn.isEmpty())
{ // Read key, print if not in whitelist.
int key = StdIn.readInt();
if (rank(key,whitelist)<0)
StdOut.println(key);
}
}
}