欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

3.3.1查找最大和次大元素

程序员文章站 2022-05-12 17:28:44
...
#include <bits/stdc++.h>
using namespace std;

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

void disp(int arr[], int n) {
	for(int i = 0; i < n; i++)
		cout << " "<< arr[i];
	cout << endl;
}

int main(){
	int a[] = {2, 5, 1, 7, 10, 6, 9, 4, 3, 8};
	int n = sizeof(a) /sizeof(a[0]);
	int max1; 
	int max2;
	cout << "前:";
	disp(a, n);
	solve(a, 0, n -1, max1, max2);
	cout << "最大数为: " << max1 << endl; 
	cout << "次最大数为: " << max2 << endl;
	return 0;
}