# 算法 - 二分查找

 1 public class BinarySearch<T extends Comparable> {
2
3     /**
4      * 递归二分查找
5      *
6      * @param arr    数组
7      * @param left   左标
8      * @param right  右标
9      * @param target 查找值
10      * @return 找到返回下标，未找到返回-1
11      */
12     public int binarySearch(T[] arr, int left, int right, T target) {
13         if (right < left) {
14             return -1;
15         }
16         int middle = (right - left) / 2 + left;
17         if (target.compareTo(arr[middle]) == 0) {
18             return middle;
19         } else if (target.compareTo(arr[middle]) < 0) {
20             return binarySearch(arr, left, middle - 1, target);
21         } else {
22             return binarySearch(arr, middle + 1, right, target);
23         }
24     }
25
26     public int binarySearch(T[] arr, T target) {
27         return binarySearch(arr, 0, arr.length - 1, target);
28     }
29
30     /**
31      * while方式二分查找
32      *
33      * @param arr    数组
34      * @param target 查找值
35      * @return 找到返回下标，未找到返回-1
36      */
37     public int whileBinarySearch(T[] arr, T target) {
38         int left = 0;
39         int right = arr.length - 1;
40         while (left <= right) {
41             int middle = (right - left) / 2 + left;
42             if (target.compareTo(arr[middle]) == 0) {
43                 return middle;
44             }
45             if (target.compareTo(arr[middle]) < 0) {
46                 right = middle - 1;
47             }
48             if (target.compareTo(arr[middle]) > 0) {
49                 left = middle + 1;
50             }
51         }
52         return -1;
53     }
54
55     public static void main(String[] args) {
56         Integer[] arr = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
57         BinarySearch bs = new BinarySearch();
58         System.out.println(bs.binarySearch(arr, 6));
59         System.out.println(bs.binarySearch(arr, 0));
60         System.out.println(bs.whileBinarySearch(arr, 11));
61         System.out.println(bs.whileBinarySearch(arr, 3));
62         String[] stingArr = new String[]{"A","B","B","D","E","F","G",};
63         System.out.println(bs.whileBinarySearch(stingArr, "B"));
64         System.out.println(bs.whileBinarySearch(stingArr, "C"));
65         System.out.println(bs.binarySearch(stingArr, "G"));
66     }
67
68 }

posted @ 2020-04-30 17:39  SamNicole1809  阅读(88)  评论(0编辑  收藏