首先,我们将一对输入元素进行比较,然后把较小的值与最小值比较,较大值与最大值比较。这样,每两个元素共需3次比较。
如果n是奇数,就把最大最小值的初值都设为第一个元素的值,然后成对处理剩下的元素;如果n是偶数,则先比较前两个元素,决定最大最小值的初值,然后成对处理剩下的元素。
#include "stdafx.h"
struct Max_Min
{
public:
int max;
int min;
};
struct Max_Min MaxAndMin(int a[], int len)
{
Max_Min num;
int i = 0;
if (len%2)
{
num.max = num.min = a[0];
i = 1;
}
else
{
if (a[0]>a[1])
{
num.max = a[0];
num.min = a[1];
}
else
{
num.max = a[1];
num.min = a[0];
}
i = 2;
}
for (i; i < len; i += 2)
{
int max_temp;
int min_temp;
if (a[i] > a[i + 1])
{
max_temp = a[i];
min_temp = a[i + 1];
}
else
{
max_temp = a[i + 1];
min_temp = a[i];
}
num.max = num.max > max_temp ? num.max : max_temp;
num.min = num.min < min_temp ? num.min : min_temp;
}
return num;
}
int _tmain(int argc, _TCHAR* argv[])
{
Max_Min num;
int a[] = { 12, 5, 11, 7, 124, 456, 22, 5, 23 };
int len = sizeof(a) / 4;
num = MaxAndMin(a, len);
cout << num.max << endl;
cout << num.min << endl;
return 0;
}