c++三分算法思想及实现方法

发布于:2024-03-18 ⋅ 阅读:(100) ⋅ 点赞:(0)

C++中的三分算法(Ternary Search Algorithm)是一种用于在有序数组或函数中寻找最大值或最小值的搜索算法。它类似于二分搜索,但不同之处在于它将搜索区间分成三个部分而不是两个部分。

以下是三分搜索算法的基本思想和实现步骤:

基本思想:

  1. 将搜索范围分成三个部分。
  2. 检查函数在搜索范围的1/3和2/3处的值。
  3. 如果目标值在1/3处的值的左侧,则将搜索范围缩小为左侧1/3的部分。如果目标值在2/3处的值的右侧,则将搜索范围缩小为右侧1/3的部分。
  4. 重复以上步骤,直到搜索范围足够小或者满足某个终止条件。

实现步骤:

  1. 定义搜索范围的起始点和终点。
  2. 使用一个循环或递归来不断缩小搜索范围,直到满足终止条件。
  3. 在每一步中,计算中间点1/3和2/3处的值,并比较目标值。
  4. 根据目标值与中间值的关系,缩小搜索范围。
  5. 当搜索范围足够小时,返回最终结果。

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 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函数采用递归的方式执行三分搜索。您也可以选择使用迭代的方法来实现。

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到