写一段C++语言的二分答案
时间: 2024-02-28 08:36:48 浏览: 44
Sure, here's an example of binary search algorithm in C language:
int binary_search(int arr[], int start, int end, int target) {
while (start <= end) {
int mid = start + (end - start) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1; // target not found
}
You can call the above function in your main program and provide the necessary inputs: array to search in, start and end indices, and the target value. The function will return the index of the target value in the array, or -1 if target is not found.
阅读全文