二分查找
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找相关的知识,希望对你有一定的参考价值。
一.适用情形
二分查找,又称折半查找,优点是比较次数少,查找速度快,平均性能好;
其缺点是要求待查表为有序表,且插入删除困难。
因此,折半查找方法适用于不经常变动而查找频繁的有序列表。
二.Java语言对二分查找的实现
1.循环方式实现
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 }
2.递归方式实现
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 }
3.JDK中的实现(java.util.Arrays类,采用的是循环方式,附带range checks)
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. }
以上是关于二分查找的主要内容,如果未能解决你的问题,请参考以下文章