常见的二分查找:
int binary_search(int *arr, int n, int x) {
int head = 0, tail = n - 1, mid;
while (head <= tail) {
mid = (head + tail) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] < x)
head = mid + 1;
else
tail = mid - 1;
}
return -1;
}
改为递归:
int binary_search_recursion(int *arr, int l, int r, int x) {
if (l > r) return -1;
int mid = (l + r) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] < x)
l = mid + 1;
else
r = mid - 1;
binary_search_recursion(arr, l, r, x);
}
评论 (0)