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 大于当前位置值则在数列的后半段中继续查找,直到找到为止。
相关推荐
zangdaiyang 2020-07-04
Happyunlimited 2020-02-21
rein0 2020-01-08
tlsmile 2020-01-07
风吹夏天 2020-01-07
yuanran0 2019-10-28
ytp00ytp 2019-09-07
ateacup 2012-02-25
wuyindengliu 2014-09-01
CallmeZhe 2019-01-02
hexianhao 2018-09-21
frankwtq 2017-01-18
SunnyFuture 2018-03-12
humothetrader 2018-01-15
jiayuqicz 2017-12-11
pythonpycharm 2017-12-04
wangxiaohua 2015-07-18