根据书中第四种思路得到下面的源码:
#include <iostream>
using namespace std;
struct mytype{//定义返回类型
int x,y;
mytype(int m,int n) : x(m),y(n){}
};
mytype Search(int arr[],int b,int e)
{
int maxV,minV;
if (e - b <= 1)
{
int max = arr[e] < arr[b] ? arr[b] : arr[e];
int min = arr[e] < arr[b] ? arr[e] : arr[b];
cout<<"..."<<max<<" ,"<<min<<"..."<<endl<<endl;
return mytype(max,min);
}
mytype strL = Search(arr,b,(b + e) / 2); //前半部分递归
mytype strR = Search(arr,(b + e) / 2 + 1,e);//后半部分递归
maxV = strL.x > strR.x ? strL.x : strR.x;//求max
minV = strL.y < strR.y ? strL.y : strR.y;//求min
return mytype(maxV,minV);
}
int main()
{
cout << "input several numbers:" << endl;
int b[100];
int i = 0,j;
while(cin >> j)
{
b[i] = j;
i++;
}
cout << "the maxV and minV are:" << endl;
mytype result = Search(b,0,i - 1);
cout << "执行结果:" << result.x << " ," << result.y << endl;
i = 0;
system("pause");
return 0;
}