-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.java
67 lines (63 loc) · 1.85 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
import java.util.Arrays;
import java.util.Comparator;
/**
* Binary search.
*/
public class BinarySearch {
/**
* Returns the index of the first key in a[] that equals the search key,
* or -1 if no such key exists. This method throws a NullPointerException
* if any parameter is null.
*/
public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new NullPointerException();
}
int left = 0;
int right = a.length - 1;
while (right >= left) {
int middle = left + (right - left) / 2;
if(comparator.compare(key, a[middle]) < 0) {
right = middle - 1;
}
else if (comparator.compare(key, a[middle]) > 0) {
left = middle + 1;
}
else if (middle == left) {
return middle;
}
else {
right = middle;
}
}
return -1;
}
/**
* Returns the index of the last key in a[] that equals the search key,
* or -1 if no such key exists. This method throws a NullPointerException
* if any parameter is null.
*/
public static <Key> int lastIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new NullPointerException();
}
int left = 0;
int right = a.length - 1;
while (right >= left) {
int middle = left + (right - left) / 2;
if(comparator.compare(key, a[middle]) < 0) {
right = middle - 1;
}
else if (comparator.compare(key, a[middle]) > 0) {
left = middle + 1;
}
else if (middle == right) {
return middle;
}
else {
left = middle;
}
}
return -1;
}
}