-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
51 lines (47 loc) · 1.48 KB
/
BinarySearch.java
File metadata and controls
51 lines (47 loc) · 1.48 KB
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
import java.util.*;
public class BinarySearch {
public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> c) {
if(a == null || key == null || c == null)
throw new NullPointerException("Argument is null");
if(a.length == 0)
return -1;
if(c.compare(a[0], key) == 0)
return 0;
int result = -1;
int lo = 0;
int hi = a.length - 1;
while(lo <= hi) {
int mid = lo + (hi - lo) / 2;
if(c.compare(key, a[mid]) == 0) {
result = mid;
hi = mid - 1;
} else if(c.compare(key, a[mid]) < 0)
hi = mid - 1;
else
lo = mid + 1;
}
return result;
}
public static <Key> int lastIndexOf(Key[] a, Key key, Comparator<Key> c) {
if(a == null || key == null || c == null)
throw new NullPointerException("Argument is null");
if(a.length == 0)
return -1;
if(c.compare(a[a.length - 1], key) == 0)
return a.length - 1;
int result = -1;
int lo = 0;
int hi = a.length - 1;
while(lo <= hi) {
int mid = lo + (hi - lo) / 2;
if(c.compare(key, a[mid]) == 0) {
result = mid;
lo = mid + 1;
} else if(c.compare(key, a[mid]) < 0)
hi = mid - 1;
else
lo = mid + 1;
}
return result;
}
}