二分法查找升序和降序集合

二分法查找list并进行数据的增删改
系统提供的方法是对升序list或数组进行查找
返回的值>0则代表找到,小于0表示没有找到
如果小于0 那么取反则是数据需要插入的位置
list和数组的查找系统提供的方法为 :

Collections.binarySearch()    
ContainerHelpers.binarySearch()  

public class Test {
    /**
    * 对降序list进行查找
    */
    private static 
    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)
                high = mid - 1;
            else if (cmp > 0)
                low = mid + 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found
    }

  public static void test() {
        ArrayList arrayList = new ArrayList<>();
        arrayList.add(1.2);
        arrayList.add(1.4);
        arrayList.add(1.5);
        arrayList.add(1.62);
        arrayList.add(1.91);
        arrayList.add(6.23);
        arrayList.add(12.12);
        Log.d("lpf", "5.8 : " + Collections.binarySearch(arrayList, 5.8));
        Log.d("lpf", "6.23 : " + Collections.binarySearch(arrayList, 6.23));
        Log.d("lpf", "13 : " + Collections.binarySearch(arrayList, 13.00));

        Log.d("lpf", "------------------------");
        ArrayList  list = new ArrayList<>();
        list.add(12.12);
        list.add(6.23);
        list.add(1.91);
        list.add(1.62);
        list.add(1.5);
        list.add(1.4);
        list.add(1.2);
        Log.d("lpf", "5.8 : " + indexedBinarySearch(list, 5.8));
        Log.d("lpf", "6.23 : " + indexedBinarySearch(list, 6.23));
        Log.d("lpf", "13 : " + indexedBinarySearch(list, 13.00));
    }
}

你可能感兴趣的:(java,android)