forked from burakbayramli/books
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.java
87 lines (79 loc) · 2.7 KB
/
BinarySearch.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*************************************************************************
* Compilation: javac BinarySearch.java
* Execution: java BinarySearch whitelist.txt < input.txt
* Dependencies: In.java StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/11model/tinyW.txt
* http://algs4.cs.princeton.edu/11model/tinyT.txt
* http://algs4.cs.princeton.edu/11model/largeW.txt
* http://algs4.cs.princeton.edu/11model/largeT.txt
*
* % java BinarySearch tinyW.txt < tinyT.txt
* 50
* 99
* 13
*
* % java BinarySearch largeW.txt < largeT.txt | more
* 499569
* 984875
* 295754
* 207807
* 140925
* 161828
* [367,966 total values]
*
*************************************************************************/
import java.util.Arrays;
/**
* The <tt>BinarySearch</tt> class provides a static method for binary
* searching for an integer in a sorted array of integers.
* <p>
* The <em>rank</em> operations takes logarithmic time in the worst case.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/11model">Section 1.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class BinarySearch {
/**
* This class should not be instantiated.
*/
private BinarySearch() { }
/**
* Searches for the integer key in the sorted array a[].
* @param key the search key
* @param a the array of integers, must be sorted in ascending order
* @return index of key in array a[] if present; -1 if not present
*/
public static int rank(int key, int[] a) {
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;
}
/**
* Reads in a sequence of integers from the whitelist file, specified as
* a command-line argument. Reads in integers from standard input and
* prints to standard output those integers that do *not* appear in the file.
*/
public static void main(String[] args) {
// read the integers from a file
In in = new In(args[0]);
int[] whitelist = in.readAllInts();
// sort the array
Arrays.sort(whitelist);
// read integer key from standard input; print if not in whitelist
while (!StdIn.isEmpty()) {
int key = StdIn.readInt();
if (rank(key, whitelist) == -1)
StdOut.println(key);
}
}
}