[英]How can I adapt a search algorithm in an array of higher and lower numbers to complexity (3n / 2) - 2?
I have a program which searches for the largest and smallest number in an array of n elements in the C ++ language. 我有一个程序,用C ++语言在n个元素的数组中搜索最大和最小的数字。 What I want to do is to decrease the complexity of the algorithm a
(3n / 2) - 2
, which currently does not meet this complexity. 我想做的是降低算法a
(3n / 2) - 2
的复杂度,该算法目前无法满足这种复杂度。
This complexity is in the worst case 在最坏的情况下,这种复杂性
My question is how can I leave this algorithm to the aforementioned complexity formula? 我的问题是如何将这种算法留给上述复杂度公式? Or what can I modify, delete and add to comply with that condition?
或者我可以修改,删除和添加哪些内容以符合该条件?
Thank you. 谢谢。 The comparison algorithm is as follows:
比较算法如下:
#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;
}
UPDATE: The algorithm has a complexity equation of 5n-2
, I must lower its complexity to (3n / 2) - 2
更新:该算法的复杂度方程为
5n-2
,我必须将其复杂度降低为(3n / 2) - 2
This solution uses the Divide and Conquer
paradigm. 此解决方案使用
Divide and Conquer
范式。
I based this answer from this website and there you can see the explanation of why this will take (3n / 2) - 2
comparisons. 我从这个网站上获得了这个答案,在那里您可以看到为什么要进行
(3n / 2) - 2
比较的解释。
To understand how it works, I suggest getting a pen and paper and follow the code, using a smaller input (eg: {3,2,1,0}). 为了理解它是如何工作的,我建议您使用一支较小的输入(例如:{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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.