Divide-and-conquer algorithm-----Two-minute maximum minimum

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.