1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public static int bsearch(int[] arr, int n, int value) { int low = 0; int high = n-1;
while (low <= high) { int mid = low + (high-low)/2;
if (arr[mid] == value) { return mid; } else if (arr[mid] < value) { low = mid + 1; } else { high = mid - 1; } } return -1; }
// 递归实现 public static int bsearch(int[] arr, int low, int high, int value) { if (low > high) return -1;
int mid = low + (high-low)/2; if (arr[mid] == value) { return mid; } else if (arr[mid] > value) { return bsearch(arr, low, mid-1, value); } else { return bsearch(arr, mid+1, high, value); } }
|