Collections.binarySearch

首先,RandomAccess接口用來標記一個List是支持高性能隨機訪問的,而BINARYSEARCH_THRESHOLD是Collections的一個常量(5000),它是二分查找的閥值。   binarySearch提供一個二分法查找的方法,參數是List和一個須要查找的key:   public static <T>  int binarySearch(List<? extends Comparable<? super T>> list, T key) 當一個List支持高性能隨機訪問,或者大小小於二分查找閥值的時候,按下標二分查找;不然,用迭代器實現二分查找:         if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)             return Collections.indexedBinarySearch(list, key);         else             return Collections.iteratorBinarySearch(list, key); ------------------------------------------------------------------------------------------ indexedBinarySearch方法在比較的時候會按照下標來獲取列表中的元素:             Comparable<? super T> 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 以上的步驟都在循環中執行,循環條件是事先定義的最小下標小於最大下標:         int low = 0;         int high = list.size()-1;         while (low <= high) {...} 每次比較前,把mid置爲low和high的中間位置,若是low+high是奇數,則對(low + hight) / 2向下取整。這個過程能夠用向右移位完成:  int mid = (low + high) >>> 1; 最後,若是找不到,則返回一個負數:return -(low + 1); ---------------------------------------------------------------------------- iteratorBinarySearch的算法和上面徹底一致,只是要用迭代器取出List中的元素         ListIterator<? extends Comparable<? super T>> i = list.listIterator();         ...         Comparable<? super T> midVal = get(i, mid); --------------------------------------------------------------------------- Collections還提供了另外兩個多態方法,在上述兩個二分查找方法中增長一個參數Comparator,在比較元素的時候使用這個特定的比較器,其餘實現徹底一致。所以,也就提供了另外一個binarySearch的公共方法,在原先的方法里加上比較器參數: public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {         if (c==null)             return binarySearch((List) list, key);         if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)             return Collections.indexedBinarySearch(list, key, c);         else             return Collections.iteratorBinarySearch(list, key, c);     }
相關文章
相關標籤/搜索