Skip to content

Commit 9535471

Browse files
committed
binary search
1 parent b55b4fd commit 9535471

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import java.util.Arrays;
2+
3+
/**
4+
* The class provides a static method for binary searching for an integer in a sorted array of integers.
5+
* The `indexOf` operations takes logarithmic time in the worst case.
6+
*
7+
*/
8+
public class BinarySearch {
9+
private BinarySearch {}
10+
11+
/**
12+
* Returns the index of the specified key in the specified array.
13+
*
14+
* @param a: the array if integers, must be sorted in ascending order
15+
* @param key: the search key
16+
* @return the index of key in array if present, -1 otherwise
17+
*
18+
*/
19+
public static int indexOf(int[] a, int key) {
20+
int lo = 0;
21+
int hi = a.length - 1;
22+
while(lo <= hi) {
23+
// key is in a[lo, hi] or not exist
24+
int mid = (hi - lo) / 2 + lo;
25+
if(key < a[mid])
26+
hi = mid - 1;
27+
else if(key > a[mid])
28+
lo = mid + 1;
29+
else
30+
return mid;
31+
}
32+
return -1;
33+
}
34+
35+
/**
36+
* Return the index of the specified key in the specified array.
37+
* This function is poorly named because it doesn't give the rank
38+
* if the array has duplicate keys or if the key isn't in the array.
39+
*
40+
* @param key: the search key
41+
* @param a: the array of integers, must be sorted in ascending order
42+
* @return index of key in array if exist, -1 otherwise
43+
*
44+
*/
45+
@Deprecated
46+
public static int rank(int key, int[] a) {
47+
return indexOf(a, key);
48+
}
49+
50+
/**
51+
* Reads in a sequence of integers from the whitelist file, specific as
52+
* a command-line argument; reads in integers from standard input;
53+
* prints to standard output those integers that don't appear in the file.
54+
*
55+
* @param args: the command-line arguments
56+
*
57+
*/
58+
public static void main(String[] args) {
59+
// read the integers from file
60+
In in = new In(args[0])
61+
int[] whitelist = in.readAllInts();
62+
63+
// sort
64+
Arrays.sort(whitelist);
65+
66+
// read integer key from standard input, print if not in whitelist
67+
while(!StdIn.isEmpty()) {
68+
int key = StdIn.readInt();
69+
if(BinarySearch.indexOf(whitelist, key) == -1)
70+
StdOut.println(key);
71+
}
72+
}
73+
}

0 commit comments

Comments
 (0)