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


    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++实现:

    1. // Ternary Search Algorithm in C++
    2. #include
    3. using namespace std;
    4. // Function to perform ternary search
    5. int ternarySearch(int arr[], int left, int right, int key) {
    6. while (right >= left) {
    7. // Find mid1 and mid2
    8. int mid1 = left + (right - left) / 3;
    9. int mid2 = right - (right - left) / 3;
    10. // Check if key is present at any mid
    11. if (arr[mid1] == key) {
    12. return mid1;
    13. }
    14. if (arr[mid2] == key) {
    15. return mid2;
    16. }
    17. // Since key is not present at mid,
    18. // check in which region it is present
    19. // then repeat the search operation in that region
    20. if (key < arr[mid1]) {
    21. // The key lies in the left-third portion
    22. right = mid1 - 1;
    23. } else if (key > arr[mid2]) {
    24. // The key lies in the right-third portion
    25. left = mid2 + 1;
    26. } else {
    27. // The key lies in the middle-third portion
    28. left = mid1 + 1;
    29. right = mid2 - 1;
    30. }
    31. }
    32. // Key not found
    33. return -1;
    34. }
    35. // Driver code
    36. int main() {
    37. int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    38. int n = sizeof(arr) / sizeof(arr[0]);
    39. int key = 5;
    40. int result = ternarySearch(arr, 0, n - 1, key);
    41. (result == -1) ? cout << "Element is not present in array"
    42. : cout << "Element is present at index " << result;
    43. return 0;
    44. }

    在上面的实现中,ternarySearch函数采用递归的方式执行三分搜索。您也可以选择使用迭代的方法来实现。

  • 相关阅读:
    J-Tech Talk|以型搜型:3D模型表征助力3D神经搜索!
    nodejs毕业设计基于Nodejs实现的心理健康咨询微信小程序
    SystemVerilog
    计算机考研 | 2020年 | 计算机组成原理真题
    docker下安装fastdfs,并使用java操作api
    IP地址定位是什么?有哪些优缺点?
    C和指针 第12章 使用结构和指针 12.2 单链表
    小白备战大厂算法笔试(二)——数组、链表、列表
    基于STM32人脸识别系统方案设计(程序代码+设计说明书)
    路由 知识
  • 原文地址:https://blog.csdn.net/m0_63558278/article/details/136746484