标签:data bin color tps logs from argument blog key
二分查找,又称折半查找,优点是比较次数少,查找速度快,平均性能好;
其缺点是要求待查表为有序表,且插入删除困难。
因此,折半查找方法适用于不经常变动而查找频繁的有序列表。
1 public static int loopBinarySearch(int[] arr, int key) { 2 int low = 0; 3 int high = arr.length - 1; 4 while (low <= high) { 5 int mid = low + (high - low) / 2; 6 if (arr[mid] == key) 7 return mid; 8 else if (arr[mid] < key) { 9 low = mid + 1; 10 } else { 11 high = mid - 1; 12 } 13 } 14 return -1; 15 }
1 public static int recursionBinarySearch(int[] arr, int key) { 2 int low = 0; 3 int high = arr.length - 1; 4 return recursionBinarySearch(arr, key, low, high); 5 } 6 7 private static int recursionBinarySearch(int[] arr, int key, int low, int high) { 8 if (low > high) return -1; 9 int mid = low + (high - low) / 2; 10 if (arr[mid] == key) 11 return mid; 12 else if (arr[mid] < key) { 13 return recursionBinarySearch(arr,key,mid + 1,high); 14 } else { 15 return recursionBinarySearch(arr,key,low,mid - 1); 16 } 17 }
public static int binarySearch(int[] a, int fromIndex, int toIndex, int key) { rangeCheck(a.length, fromIndex, toIndex); return binarySearch0(a, fromIndex, toIndex, key); } private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } if (fromIndex < 0) { throw new ArrayIndexOutOfBoundsException(fromIndex); } if (toIndex > arrayLength) { throw new ArrayIndexOutOfBoundsException(toIndex); } } 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. }
标签:data bin color tps logs from argument blog key
原文地址:http://www.cnblogs.com/assange/p/7414156.html