我怎样才能使搜索算法适应更高和更低数字的数组以适应复杂度 (3n / 2) - 2?

How can I adapt a search algorithm in an array of higher and lower numbers to complexity (3n / 2) - 2?

我有一个程序,用C++语言搜索n个元素的数组中的最大和最小数。我想做的是降低算法a的复杂度(3n / 2) - 2,目前不满足这个复杂度

这个复杂度是最坏的情况

我的问题是如何将此算法留给上述复杂度公式?或者我可以修改、删除和添加什么以符合该条件?

谢谢。 比较算法如下:

#include <iostream>
using namespace std;
int main(){
    int arreglo[10] = {9,8,7,6,5,4,3,2,1,0};
    int menor =0, mayor =0, comparaciones=0;
    menor = arreglo[0], mayor = arreglo[0];
    for(int i=1;i<10;i++){
        if(arreglo[i]>mayor){
            mayor = arreglo[i];
        }
        comparaciones++;
        if(arreglo[i]<menor){
                menor = arreglo[i];
        }    
        comparaciones++;
    }
    cout<<"Mayor: "<<mayor<<" Menor: "<<menor<<" Comparaciones: "<<comparaciones;
}

更新: 该算法的复杂度方程为 5n-2,我必须将其复杂度降低到 (3n / 2) - 2

此解决方案使用 Divide and Conquer 范例。

我基于 this website 的回答,您可以在其中看到为什么需要 (3n / 2) - 2 比较的解释。

要了解它是如何工作的,我建议拿笔和纸并按照代码使用较小的输入(例如:{3,2,1,0})。

#include <iostream>
using namespace std;

int* maxMin(int* values, int begin, int end) {
    int partialSmallest, partialLargest;
    int mid, max1, min1, max2, min2;
    //Here we store Largest/Smallest
    int* result = new int[2];

    //When there's only one element
    if (begin == end) {
        partialSmallest = values[begin];
        partialLargest = values[begin];
    }
    else {
        //There is not only one element, therefore
        //We will split into two parts, and call the function recursively
        mid = (begin + end) / 2;
        // Solve both "sides"
        int* result1 = maxMin(values, begin, mid);
        int* result2 = maxMin(values, mid+1, end);

        max1 = result1[0];
        min1 = result1[1];

        max2 = result2[0];
        min2 = result2[1];
        //Combine the solutions.
        if (max1 < max2)
            partialLargest = max2;
        else
            partialLargest = max1;
        if (min1 < min2)
            partialSmallest = min1;
        else
            partialSmallest = min2;
    }

    result[0] = partialLargest;
    result[1] = partialSmallest;
    return result;
}

int main(){
    int values[10] = {9,8,7,6,5,4,3,2,1,0};
    int* finalResult = maxMin(values, 0, 9);
    cout << "Largest: " << finalResult[0] << " Smallest: " << finalResult[1];
}