-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
36 lines (28 loc) · 845 Bytes
/
BinarySearch.java
File metadata and controls
36 lines (28 loc) · 845 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
package binary_search;
import java.util.ArrayList;
// 18.5 Алгоритм бинарного поиска
// Task 18.1.3
public class BinarySearch {
private ArrayList<String> list;
public BinarySearch(ArrayList<String> list) {
this.list = list;
}
public int search(String query) {
return search(query, 0, list.size() - 1);
}
private int search(String query, int from, int to) {
if (to < from) {
return -1;
}
// int middle = (from + to) / 2;
int middle = from + (to - from) / 2;
int comparison = query.compareTo(list.get(middle));
if (comparison == 0) {
return middle;
}
if (comparison > 0) {
return search(query, middle + 1, to);
}
return search(query, from, middle - 1);
}
}