//已知S有N个元素,求S的最大元素
#include<iostream>
using namespace std;
int max(int a,int b)
{
return (a>b?a:b);
}
int searchmax(int s[],int left,int right)
{
if(left == right || (left+1) == right) //剩下两个元素或一个元素
{
int max1=s[left];
int max2=s[right];
return max(max1,max2);
}
else
{
int middle = (left+right)/2;
int max1 = searchmax(s,left,middle);
int max2 = searchmax(s,middle+1,right);
return(max(max1,max2));
}
}
int main()
{
int a[] = {100,30,7,50,9,90};
int n= sizeof a/sizeof(*a); //元素个数
for(int i = 0;i < n;i++)
cout<<a[i]<<" ";
cout<<endl;
int max = searchmax(a,0,n-1);
cout<<"max= "<<max<<endl;
}
评论