Example 1: Give n real numbers, ask for their maximum and minimum, and ask for a smaller number of comparisons.
Idea: Use recursive calling functions to make the following judgments in the function:
1 if Left==right (only one number) Max and Min are for this number
2 if left==right-1 (only two numbers) Max is larger, Min is the smaller
3 In addition to the above two define the intermediate value D, in the recursive call left to D and d+1 to right function, Max is two functions return the maximum value, min is the minimum value
Core ideas above
Original code:
#include <iostream>
using namespace Std;
int A[132133],maxx,minn;
void qq (int left1,int right1,int &maxx,int &minn)
{
int d=0,max1=0,max2=0,min1=0,min2=0;
if (left1==right1) {
MAXX=A[LEFT1];
MINN=A[LEFT1];
}
if (right1==left1+1) {
Maxx=max (a[left1],a[right1]);
Minn=min (a[left1],a[right1]);
}
else{
D= (LEFT1+RIGHT1)/2;
QQ (LEFT1,D,MAX1,MIN1);
QQ (D+1,RIGHT1,MAX2,MIN2);
Maxx=max (MAX1,MAX2);
Minn=min (min1,min2);
}
}
int main ()
{
int n;
cin>>n;
for (int i=1;i<=n;i++)
cin>>a[i];
QQ (1,n,maxx,minn);
cout<<maxx<< "" <<minn;
return 0;
}
Error reason: The idea is correct, but 11 rows of if before the else, resulting in 15 rows of else is only built on the if of 11 rows, and the idea does not match, the if before filling in the else can
Divide-and-conquer algorithm-----Two-minute maximum minimum