实现二分搜索的递归与非递归程序用C++实现的伪代码
时间: 2024-05-01 11:17:57 浏览: 86
C语言数据结构中二分查找递归非递归实现并分析
Sure, 下面是用 C 实现二分搜索的递归和非递归程序的伪代码:
递归程序:
```
int binary_search_recursive(int arr[], int left, int right, int target) {
if (left > right) {
return -1;
}
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
return binary_search_recursive(arr, left, mid - 1, target);
} else {
return binary_search_recursive(arr, mid + 1, right, target);
}
}
```
非递归程序:
```
int binary_search_iterative(int arr[], int length, int target) {
int left = 0;
int right = length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
```
阅读全文