本文共 2821 字,大约阅读时间需要 9 分钟。
1,Arrays 中 实现的二分查找
public static int binarySearch(int[] a, int fromIndex, int toIndex, int key) { rangeCheck(a.length, fromIndex, toIndex); // 边界测试 return binarySearch0(a, fromIndex, toIndex, key); // private method } // Like public version, but without range checks. 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. // 没有找到的话,返回的就是插入位置(负数) }
2,Collections 中的二分查找实现
public staticint binarySearch(List > list, T key) { if (list instanceof RandomAccess || list.size() int indexedBinarySearch(List > list, T key) { int low = 0; int high = list.size()-1; while (low <= high) { int mid = (low + high) >>> 1; Comparable midVal = list.get(mid); int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } private static int iteratorBinarySearch(List > list, T key) { int low = 0; int high = list.size()-1; ListIterator > i = list.listIterator(); while (low <= high) { int mid = (low + high) >>> 1; Comparable midVal = get(i, mid); // 注意: i 这个 iterator 在查找过程中没有再重新初始化 int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } /** * Gets the ith element from the given list by repositioning the specified * list listIterator. */ private static T get(ListIterator i, int index) { T obj = null; int pos = i.nextIndex(); if (pos <= index) { do { obj = i.next(); // 往后找 } while (pos++ < index); } else { do { obj = i.previous(); // 往前找 } while (--pos > index); } return obj; }
转载地址:http://xcsgx.baihongyu.com/