二分查找(Binary Search)是一种在有序数组或列表中查找特定元素的搜索算法。该算法比较要搜索的值和数组的中间元素。如果要搜索的值小于中间元素,则在数组的左半部分继续搜索;如果要搜索的值大于中间元素,则在数组的右半部分继续搜索。通过不断缩小搜索范围,最终可以在O(log n)的时间复杂度内找到目标元素,是一种高效的搜索算法。
C++中实现二分查找的示例代码:
#include <iostream>
#include <vector>
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; // Target not found
}
int main() {
std::vector<int> arr = {1, 3, 5, 7, 9, 11, 13, 15};
int target = 7;
int result = binarySearch(arr, target);
if (result != -1) {
std::cout << "Target found at index: " << result << std::endl;
} else {
std::cout << "Target not found" << std::endl;
}
return 0;
}
这段代码演示了一个简单的二分查找函数,用于在一个有序整数数组中查找特定的目标值。
示例二 查找字符串:
二分查找通常是用于在有序数组中查找数值类型的数据,而不是用于在字符串数组中查找字符串。但是,如果你需要在有序的字符串数组中查找特定的字符串,你可以自定义比较函数来进行二分查找。以下是一个示例代码:
#include <iostream>
#include <vector>
#include <string>
int binarySearchString(std::vector<std::string>& arr, const std::string& target) {
int left = 0;
int right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int cmp = target.compare(arr[mid]);
if (cmp == 0) {
return mid;
} else if (cmp < 0) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1; // Target not found
}
int main() {
std::vector<std::string> arr = {"apple", "banana", "cherry", "orange", "strawberry"};
std::string target = "cherry";
int result = binarySearchString(arr, target);
if (result != -1) {
std::cout << "Target found at index: " << result << std::endl;
} else {
std::cout << "Target not found" << std::endl;
}
return 0;
}
这段代码演示了一个简单的二分查找函数,用于在一个有序的字符串数组中查找特定的目标字符串。