标签:
二分查找可以说是在经典不过的查找算法了,比如JAVA的库函数里,就有相应的代码实例。如下写出两个版本的二分查找,非递归和递归的
非递归的
public int binarySearch1(int[] a, int key) { int low = 0; int high = a.length-1; int mid; while (low <= high) { mid = (high + low) >>> 1; if (key < a[mid]) { high = mid - 1; } else if (key > a[mid]) { low = mid + 1; } else { return mid; } } return -1; }
递归版的
public int binarySearch2(int[] a, int low, int high, int key) { if (low <= high) { int mid = (high + low) >>> 1; if (key == a[mid]) { return mid; } else if (key < a[mid]) { return binarySearch2(a, low, mid-1, key); } else { return binarySearch2(a, mid+1, high, key); } } return -1; }
标签:
原文地址:http://blog.csdn.net/my_jobs/article/details/43566661