你可以使用封装来写一个可能的二分法的c++代码吗
时间: 2024-04-29 15:27:11 浏览: 15
当然可以!以下是一个使用封装实现的可能的二分法的C代码:
```c
#include <stdio.h>
// 封装二分查找函数
int binary_search(int arr[], int n, int target) {
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 3, 5, 7, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 5;
int res = binary_search(arr, n, target);
if (res == -1) {
printf("没有找到 %d\n", target);
} else {
printf("%d 在数组中的下标是 %d\n", target, res);
}
return 0;
}
```
该代码中,我们使用了 `binary_search` 函数来实现二分查找,将该函数封装起来,可以提高代码的可读性和可维护性。