-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
33 lines (26 loc) · 898 Bytes
/
BinarySearch.java
File metadata and controls
33 lines (26 loc) · 898 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
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BinarySearch {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<>();
for (int i = 0; i < 100; i++) ex.add(i);
System.out.println(findNumber(34, ex));
}
public static int findNumber(int find, List<Integer> list) {
int result = 0;
int begin = 0, end = list.size() - 1;
Collections.sort(list);
if (!list.contains(find)) return 0;
while (begin <= end) {
int middleIdx = (end + begin)/2;
if (find > list.get(middleIdx)) begin = middleIdx;
else end = middleIdx;
if (find == list.get(middleIdx)) {
result = list.get(middleIdx);
break;
}
}
return result;
}
}