下面是一个示例代码实现C++中的二分查找算法:
#include <vector>
#include <iostream>
int binarySearch(std::vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
std::vector<int> arr = {1, 3, 5, 7, 9, 11, 13, 15};
int target = 9;
int result = binarySearch(arr, target);
if (result != -1) {
std::cout << "Element found at index: " << result << std::endl;
} else {
std::cout << "Element not found in the array" << std::endl;
}
return 0;
}
在这个示例代码中,binarySearch
函数接受一个已排序的整数数组和一个目标值作为参数,然后使用二分查找算法在数组中查找目标值。如果找到目标值,则返回该值在数组中的索引,否则返回-1。在main
函数中,我们创建了一个已排序的整数数组并调用binarySearch
函数来查找目标值9。