下面是一個示例代碼實現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。