C++中的三分算法(Ternary Search Algorithm)是一种用于在有序数组或函数中寻找最大值或最小值的搜索算法。它类似于二分搜索,但不同之处在于它将搜索区间分成三个部分而不是两个部分。
以下是三分搜索算法的基本思想和实现步骤:
- // Ternary Search Algorithm in C++
- #include
- using namespace std;
-
- // Function to perform ternary search
- int ternarySearch(int arr[], int left, int right, int key) {
- while (right >= left) {
- // Find mid1 and mid2
- int mid1 = left + (right - left) / 3;
- int mid2 = right - (right - left) / 3;
-
- // Check if key is present at any mid
- if (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 region
- if (key < arr[mid1]) {
- // The key lies in the left-third portion
- right = mid1 - 1;
- } else if (key > arr[mid2]) {
- // The key lies in the right-third portion
- left = mid2 + 1;
- } else {
- // The key lies in the middle-third portion
- left = mid1 + 1;
- right = mid2 - 1;
- }
- }
- // Key not found
- return -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函数采用递归的方式执行三分搜索。您也可以选择使用迭代的方法来实现。