#include <iostream>
#include <stdio.h>
#include <xmath.h>
#include <algorithm>
using namespace std;
void solve(int a[], int low, int high, int &max1, int &max2);
int main(){
int n=10;
int a[]={2,5,1,7,10,6,9,4,3,8};
int low=0;
int high=n-1;
int max1,max2;
solve(a,low,high,max1,max2);
printf("the largest:%d\t,the sublargest:%d",max1,max2);
}
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); //左区间求lmax1和lmax2
int rmax1,rmax2;
solve(a,mid+1,high,rmax1,rmax2);//右区间求rmax1和rmax2
if(lmax1>rmax1){
max1=lmax1;
max2=max(lmax2,rmax1);
} else{
max1=rmax1;
max2=max(lmax1,rmax2);
}
}
}
查找最大和次大元素(分治法实现)
最新推荐文章于 2022-06-03 11:19:11 发布