递归算法找最大值
#include "stdafx.h"
#include <iostream>
int findMax(int a[], int n);
int findMin(int a[], int n);
void findMinMax(const int a[], const int n,int& min,int& max);
int _tmain(int argc, _TCHAR* argv[])
{
int a[] = { 5, 3, -1, 5, 8, 999, 2, -566, -7,123456,-22333 };
int max = 0,min = 10000000;
int leng = sizeof(a) / sizeof(int);
max = findMax(a, leng);
min = findMin(a, leng);
std::cout << "max: " << max << ",min: " << min << std::endl;
min = 100000000;
max = 0;
findMinMax(a, leng, min, max);
std::cout << "max: " << max << ",min: " << min << std::endl;
system("pause");
return 0;
}
int findMax(int a[], int n)
{
if (n <= 0)
{
return 0;
}
else if (n==1)
{
return a[0];
}
int tmp1 = a[n - 1];
int tmp2 = findMax(a, n - 1);
return tmp1 >= tmp2 ? tmp1 : tmp2;
}
递归算法找最小值
int findMin(int a[], int n)
{
if (n <= 0)
{
return 0;
}
else if (n == 1)
{
return a[0];
}
int tp1 = a[n - 1];
int tp2 = findMin(a, n - 1);
return tp1 <= tp2 ? tp1 : tp2;
}
递归算法找最小最大值
void findMinMax(const int a[], const int n, int& min, int& max)
{
if (n <= 0)
{
return ;
}
else if (n == 1)
{
min = a[0];
max = a[0];
return;
}
else if (n == 2)
{
min = a[0] <= a[1] ? a[0] : a[1];
max = a[0] >= a[1] ? a[0] : a[1];
return;
}
int min1 = 100000, max1 = 0;
findMinMax(a, n - 1, min1, max1);
int tp = a[n - 1];
min = min1 <= tp ? min1 : tp;
max = max1 >= tp ? max1 : tp;
}
结果:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9eca6bdff8fb7be39078ce45f460a85f.png)