转 : http://jayzotion.javaeye.com/blog/404084
- public class TestBinSearch {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
- System.out.println(binSearch(a, 0, a.length - 1, 100));
- }
- // 二分查找递归实现
- public static int binSearch(int a[], int start, int end, int key) {
- int mid = (end - start) / 2 + start;
- if (a[mid] == key) {
- return mid;
- }
- if (start >= end) {
- return -1;
- } else if (a[mid] < key) {
- return binSearch(a, mid + 1, end, key);
- } else if (a[mid] > key) {
- return binSearch(a, start, mid - 1, key);
- }
- return -1;
- }
- // 二分查找普通循环实现
- public static int binSearch(int a[], int key) {
- int mid = a.length / 2;
- if (key == a[mid]) {
- return mid;
- }
- int start = 0;
- int end = a.length - 1;
- while (start <= end) {
- mid = (end - start) / 2 + start;
- if (key < a[mid]) {
- end = mid - 1;
- } else if (key > a[mid]) {
- start = mid + 1;
- } else {
- return mid;
- }
- }
- return -1;
- }
- }