二分查找
1/**
2 * 2分查找
3 *
4 * @author wangy
5 * @version 1.0
6 * @date 2020/6/5 / 14:23
7 */
8public class BinSearch {
9
10 public static int binSearch(ArrayList<Integer> list, int key) {
11 Collections.sort(list);
12 int low = 0;
13 int high = list.size() - 1;
14
15 while (low <= high) {
16 int mid = (low + high) / 2;
17 if (list.get(mid) > key) {
18 high = mid - 1;
19 } else if (list.get(mid) < key) {
20 low = mid + 1;
21 } else {
22 return mid;
23 }
24 }
25 return -1;
26
27 }
28
29 public static void main(String[] args) {
30 ArrayList<Integer> al = new ArrayList<>(Arrays.asList(3, 43, 23, 83, 33, 63, 93, 103, 53));
31 Collections.sort(al);
32 System.out.println(Arrays.toString(al.toArray()));
33
34 int i = BinSearch.binSearch(al, 33);
35 System.out.println(i);
36
37 System.out.println(Collections.binarySearch(al, 33));
38 }
39}