上机实验4--求序列的最大元素和最小元素

//上机实验题4 -- 求序列的最大元素和次大元素

#include<stdio.h>
void SecondElement(int a[],int low,int high,int &max,int &sec){	//
	int mid;
	int x1,x2,x3,x4;
	if(high - low < 1){	//数组中少于两个元素 
		return; 
	}
	else if(high - low == 1){	//数组中只有两个元素 
		if(a[low] < a[high]){
			max = a[high];
			sec = a[low];
		}
		else{
			max = a[low];
			sec = a[high];
		}
	}
	else{
		mid = (high - low)/2;
		SecondElement(a,low,mid,x1,x2);
		SecondElement(a,mid+1,high,x3,x4);
		if(x1 < x3){
			max = x3;
			if(x1 > x4)
				sec = x1;
			else
				sec = x4; 
		}
		else{
			max = x1;
			if(x3 > x2)
				sec = x3;
			else
				sec = x2; 
		} 
	}
}
int main(){
	int a[] = {1,2,3,4,5,6,7,8,9,10,11};
	int n = 11; 
	int max,sec;
	SecondElement(a,0,n-1,max,sec);
	printf("最大元素 = %d,次大元素 = %d\n",max,sec);
}

  

posted @ 2019-12-11 12:35  Hqx_curiosity  阅读(418)  评论(0编辑  收藏  举报