改进的二分查找

 1 import java.util.Comparator;
 2 
 3 public class MyUtil {
 4 
 5    public static <T extends Comparable<T>> int binarySearch(T[] x, T key) {
 6       return binarySearch(x, 0, x.length- 1, key);
 7    }
 8 
 9    // 使用循环实现的二分查找
10    public static <T> int binarySearch(T[] x, T key, Comparator<T> comp) {
11       int low = 0;
12       int high = x.length - 1;
13       while (low <= high) {
14           int mid = (low + high) >>> 1;
15           int cmp = comp.compare(x[mid], key);
16           if (cmp < 0) {
17             low= mid + 1;
18           }
19           else if (cmp > 0) {
20             high= mid - 1;
21           }
22           else {
23             return mid;
24           }
25       }
26       return -1;
27    }
28 
29    // 使用递归实现的二分查找
30    private static<T extends Comparable<T>> int binarySearch(T[] x, int low, int high, T key) {
31       if(low <= high) {
32         int mid = low + ((high -low) >> 1);
33         if(key.compareTo(x[mid])== 0) {
34            return mid;
35         }
36         else if(key.compareTo(x[mid])< 0) {
37            return binarySearch(x,low, mid - 1, key);
38         }
39         else {
40            return binarySearch(x,mid + 1, high, key);
41         }
42       }
43       return -1;
44    }
45 }

上面的代码中给出了折半查找的两个版本,一个用递归实现,一个用循环实现。需要注意的是计算中间位置时不应该使用(high+ low) / 2的方式,因为加法运算可能导致整数越界,这里应该使用以下三种方式之一:low + (high - low) / 2或low + (high – low) >> 1或(low + high) >>> 1(>>>是逻辑右移,是不带符号位的右移)

转自:https://blog.csdn.net/jackfrued/article/details/44921941

纸上得来终觉浅,绝知此事要躬行。
原文地址:https://www.cnblogs.com/chenglangpofeng/p/10676812.html