forked from exercism/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
40 lines (33 loc) · 932 Bytes
/
Copy pathBinarySearch.java
File metadata and controls
40 lines (33 loc) · 932 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
38
39
40
import java.util.List;
public class BinarySearch<T extends Comparable<T>> {
private List<T> array;
private int arraySize;
public BinarySearch(List<T> array) {
this.array = array;
this.arraySize = array.size();
}
public int indexOf(T value) {
return search(value);
}
public List<T> getArray() {
return array;
}
private int search(T value) {
int left = 0;
int right = this.arraySize - 1;
int middle;
T element;
while (left <= right) {
middle = (int) Math.floor(0.5 * (left + right));
element = this.array.get(middle);
if (value.compareTo(element) > 0) {
left = middle + 1;
} else if (value.compareTo(element) < 0) {
right = middle - 1;
} else {
return middle;
}
}
return -1;
}
}