版权声明:博主的博客不值钱随便转载但要注明出处 https://blog.csdn.net/easylovecsdn/article/details/82870088
输入原则:先输入要输入数据的个数,再逐个输入序列中的元素
代码:
//采用分治法寻找序列中的最大和最小值
#include <bits/stdc++.h>
#define max(x, y) x >= y ? x : y
#define min(x, y) x <= y ? x : y
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 105; //数组最大尺寸105
int a[maxn];
int Max, Min;
void init()
{
Max = -INF;
Min = INF;
}
void PartGet(int left, int right)
{
if (left == right) {
if (a[left] > Max) Max = a[left];
if (a[left] < Min) Min = a[left];
return ;
}
int mid = (left + right) / 2;
PartGet(left, mid);
PartGet(mid+1, right);
}
int main()
{
int Size = 0;
while (cin >> Size && Size) {
for (int i = 0; i < Size; i++) cin >> a[i];
init();
PartGet(0, Size-1);
cout << "MAX = " << Max << endl;
cout << "MIN = " << Min << endl;
}
return 0;
}
测试数据:
/*以下为测试数据
test1:
8
1 4 15 -3 6 12 -5 9
result1:
MAX = 15
MIN = -5
-----------------------------
test2:
7
1 4 15 -3 6 12 -5
result2:
MAX = 15
MIN = -5
-----------------------------
test3:
2
1 4
result3:
MAX = 4
MIN = 1
-----------------------------
test4:
1
-50
result4:
MAX = -50
MIN = -50
*/
测试结果: