编程之美在于算法之美,先来看看二分查找的算法:
隐藏条件:二分查找必须是有序的,从小到大,或从大到小的排序才能进行二分查找,下面来看看代码:
- package com.cn.daming;
-
- public class MainActivity {
-
-
-
-
-
- public static void main(String[] args) {
- int[] aInts = new int[]{1,3,5,8,11,14,16,24,37,47,49,56,63,83,223};
- int[] aInts2 = new int[]{322,243,211,156,98,85,79,68,53,47,38,24,13,6,2};
-
- MainActivity main = new MainActivity();
- System.out.println("aInts the reault is : " + main.binarySearch(aInts, 0, aInts.length, 24));
- System.out.println("aInts2 the reault is : " + main.binarySearch2(aInts2, 0, aInts2.length, 243));
- }
-
-
- private int binarySearch(int[] a, int start, int len, int key) {
- int high = start + len, low = start - 1, guess;
-
- while (high - low > 1) {
- guess = (high + low) / 2;
-
- if (a[guess] < key)
- low = guess;
- else
- high = guess;
- }
-
- if (high == start + len)
- return ~(start + len);
- else if (a[high] == key)
- return high;
- else
- return ~high;
- }
-
-
- private int binarySearch2(int[] a, int start, int len, int key) {
- int high = start + len, low = start - 1, guess;
-
- while (high - low > 1) {
- guess = (high + low) / 2;
-
- if (a[guess] > key)
- low = guess;
- else
- high = guess;
- }
-
- if (high == start + len)
- return ~(start + len);
- else if (a[high] == key)
- return high;
- else
- return ~high;
- }
- }
返回值就是返回要查的key的下标;
看结果如图:
2014-05-10 11:06 补充:
以上的二分查找理解起来比较费劲,下面我用个可读性强的二分查找,效率估计没有上面的高,但是程序的可读性会很强,
-
-
-
-
-
-
-
- public int binarySearch(int[] a, int key) {
- if (a.length == 0)
- return -1;
- int first = 0;
- int last = a.length - 1;
- int mid;
- while (first <= last) {
- mid = (first + last) / 2;
- if (a[mid] == key) {
- return mid;
- } else if (a[mid] > key) {
- last = mid - 1;
- } else {
- first = mid + 1;
- }
- }
- return -1;
- }
这个binarySearch()返回的是数组的下标,我验证过,没有问题的,可以直接copy过来使用的。
对二分查找求平均查找长度二分查找的过程相当与一棵二叉排序树,所以总节点数为n=2^h-1,h=Log2 (n+1)。 第i层上的节点数为2^(1-1);在等概率的情况下,平均查找长度ASL=Log2 (n+1)-1。