Algorithm || Divide and Conquer [Find the largest element and the second largest element)] #01

Divide and conquer solution [find the largest element and the second largest element]

【Problem Description】

For a given unordered sequence containing n elements, find the largest and second largest two different elements in this sequence. For example: (2, 5, 1, 4, 6, 3), the largest element is 6, and the second largest element is 5.
[Find the first and second largest numbers in the unordered array a[low...high]. The two numbers are different.

【Analysis of Algorithms】

The method of dividing in half is adopted to solve the problem.

break down:

Case 1 , if the array a[low...high] has only one data, then the largest number max1 is a[low].
Case 2 , if the array a[low...high] has two data, then compare the size of the two numbers, max1 =max(low,high), max2 =min(low,high).
Case 3 , if the array a[low...high] has 3 or more data, then use the top-down two-way merge idea, set a mid=(low+high)/2 and combine the array a[low...high] Divide into two, continue to decompose the two subsequences a[low...mid] and a[mid+1...high] recursively, and the end condition is that the length of the subsequence is 1. Find the largest element and second largest element in the left interval lmax1, lmax2 and the largest element in the right interval and the second largest element rmax1, rmax2.

merge

If the largest element in the left interval is greater than the largest element in the right interval , then max=lmax1, and then compare the size of the largest element in the right interval and the second largest element in the left interval . vice versa.

【Code】

Compilation environment : VS2017
Programming language : C++

//ex1.查找最大和次大元素
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXN 25
#define INF 0x3f3f3f3f

void Solve(int a[], int low, int high, int &max1, int &max2)
{
    
    
	if (low == high)
	{
    
    
		max1 = a[low];
		max2 = -INF;
	}
	else if (low == high - 1)
	{
    
    
		max1 = max(a[low], a[high]);
		max2 = min(a[low], a[high]);
	}
	else
	{
    
    
		int mid = (low + high) / 2;
		int lmax1, lmax2;
		Solve(a, low, mid, lmax1, lmax2);
		int rmax1, rmax2;
		Solve(a, mid + 1, high, rmax1, rmax2);
		if (lmax1 > rmax1)
		{
    
    
			max1 = lmax1;
			max2 = max(lmax2, rmax1);
		}
		else
		{
    
    
			max1 = rmax1;
			max2 = max(lmax1, rmax2);
		}
	}
}

int main()
{
    
    
	int a[MAXN];
	int n;
	int max1 = 0, max2 = 0;
	cout << "请输入数组的长度:";
	cin >> n;
	cout << "请依次输入数据:";
	for (int i = 0; i <= n; i++)
		cin >> a[i];
	Solve(a, 0, n, max1, max2);
	cout << "第一大和第二大的数据分别为:" << max1 << " ," << max2 << endl;
	system("pause");
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_43759081/article/details/121884292