码迷,mamicode.com
首页 > 其他好文 > 详细

二分查找

时间:2017-08-23 00:39:13      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:data   bin   color   tps   logs   from   argument   blog   key   

一.适用情形

二分查找,又称折半查找,优点是比较次数少,查找速度快,平均性能好;

缺点是要求待查表为有序表,且插入删除困难。

因此,折半查找方法适用于不经常变动而查找频繁的有序列表。

二.Java语言对二分查找的实现

1.循环方式实现

 1 public static int loopBinarySearch(int[] arr, int key) {
 2         int low = 0;
 3         int high = arr.length - 1;
 4         while (low <= high) {
 5             int mid = low + (high - low) / 2;
 6             if (arr[mid] == key)
 7                 return mid;
 8             else if (arr[mid] < key) {
 9                 low = mid + 1;
10             } else {
11                 high = mid - 1;
12             }
13         }
14         return -1;
15     }

 

2.递归方式实现

 1 public static int recursionBinarySearch(int[] arr, int key) {
 2         int low = 0;
 3         int high = arr.length - 1;
 4         return recursionBinarySearch(arr, key, low, high);
 5     }
 6 
 7     private static int recursionBinarySearch(int[] arr, int key, int low, int high) {
 8         if (low > high) return -1;
 9         int mid = low + (high - low) / 2;
10         if (arr[mid] == key)
11             return mid;
12         else if (arr[mid] < key) {
13             return recursionBinarySearch(arr,key,mid + 1,high);
14         } else {
15             return recursionBinarySearch(arr,key,low,mid - 1);
16         }
17     }

 3.JDK中的实现(java.util.Arrays类,采用的是循环方式,附带range checks)

    public static int binarySearch(int[] a, int fromIndex, int toIndex, int key) {
        rangeCheck(a.length, fromIndex, toIndex);
        return binarySearch0(a, fromIndex, toIndex, key);
    }

    private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) {
        if (fromIndex > toIndex) {
            throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
        }
        if (fromIndex < 0) {
            throw new ArrayIndexOutOfBoundsException(fromIndex);
        }
        if (toIndex > arrayLength) {
            throw new ArrayIndexOutOfBoundsException(toIndex);
        }
    }

    private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) {
        int low = fromIndex;
        int high = toIndex - 1;

        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = a[mid];

            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.
    }

二分查找

标签:data   bin   color   tps   logs   from   argument   blog   key   

原文地址:http://www.cnblogs.com/assange/p/7414156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!