Java JDK 二分法 分析 demo

public class Test
{

    public static void main(String[] args)
    {
        Long[] arr = new Long[100000];
        for(int i =0;i<100000;i++)
        {
            arr[i] = (long) i;
        }

        System.out.println(binarySearch(arr, 3L));
        
        Comparable midVal = (Comparable) 2L;;
        System.out.println(midVal.compareTo(2l));
    }

    private static int binarySearch(Long[] arr, long l)
    {
        return binarySearch0(arr,0,arr.length,l);
    }

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

        while (low <= high)
        {
            int mid = (low + high) >>> 1;
            Comparable midVal = (Comparable) a[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.
    }

}

算法:当数据量很大适宜采用该方法。采用二分法查找时,数据需是有序不重复的。 基本思想:假设数据是按升序排序的,对于给定值 x,从序列的中间位置开始比较,如果当前位置值等于 x,则查找成功;若 x 小于当前位置值,则在数列的前半段中查找;若 x 大于当前位置值则在数列的后半段中继续查找,直到找到为止。

相关推荐