C++中的三分算法(Ternary Search Algorithm)是一种用于在有序数组或函数中寻找最大值或最小值的搜索算法。它类似于二分搜索,但不同之处在于它将搜索区间分成三个部分而不是两个部分。
以下是三分搜索算法的基本思想和实现步骤:
基本思想:
- 将搜索范围分成三个部分。
- 检查函数在搜索范围的1/3和2/3处的值。
- 如果目标值在1/3处的值的左侧,则将搜索范围缩小为左侧1/3的部分。如果目标值在2/3处的值的右侧,则将搜索范围缩小为右侧1/3的部分。
- 重复以上步骤,直到搜索范围足够小或者满足某个终止条件。
实现步骤:
- 定义搜索范围的起始点和终点。
- 使用一个循环或递归来不断缩小搜索范围,直到满足终止条件。
- 在每一步中,计算中间点1/3和2/3处的值,并比较目标值。
- 根据目标值与中间值的关系,缩小搜索范围。
- 当搜索范围足够小时,返回最终结果。
C++实现:
// Ternary Search Algorithm in C++
#include <iostream>
using namespace std;// Function to perform ternary search
int ternarySearch(int arr[], int left, int right, int key) {while (right >= left) {// Find mid1 and mid2int mid1 = left + (right - left) / 3;int mid2 = right - (right - left) / 3;// Check if key is present at any midif (arr[mid1] == key) {return mid1;}if (arr[mid2] == key) {return mid2;}// Since key is not present at mid,// check in which region it is present// then repeat the search operation in that regionif (key < arr[mid1]) {// The key lies in the left-third portionright = mid1 - 1;} else if (key > arr[mid2]) {// The key lies in the right-third portionleft = mid2 + 1;} else {// The key lies in the middle-third portionleft = mid1 + 1;right = mid2 - 1;}}// Key not foundreturn -1;
}// Driver code
int main() {int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int n = sizeof(arr) / sizeof(arr[0]);int key = 5;int result = ternarySearch(arr, 0, n - 1, key);(result == -1) ? cout << "Element is not present in array": cout << "Element is present at index " << result;return 0;
}
在上面的实现中,ternarySearch
函数采用递归的方式执行三分搜索。您也可以选择使用迭代的方法来实现。