递归函数,用于查找 2 个整数之间的最大值

Recursive Function to find Max value between 2 integers

本文关键字:整数 之间 最大值 用于 查找 递归函数      更新时间:2023-10-16

我正在尝试创建一个递归函数,该函数在低整数和高整数之间的数组中查找最大数字。

我已经尝试过这个函数,它有助于递归地找到数组中的最大元素。我只是在如何添加到函数中遇到麻烦,该函数接受低整数和高整数以找到这 2 之间的最大值。

int findMaxRec(int A[], int n) 
{ 
// if n = 0 means whole array has been traversed 
if (n == 1) 
return A[0]; 
return max(A[n-1], findMaxRec(A, n-1)); 
} 

目标是拥有一个看起来像这样的函数:

int findMaxBetwen(int A[], int low, int high){
//Here is where I need help integrating if lets say the array is A[] = 5,6,7,8
// Call findMaxBetwen(A[], 5, 8) and the output gives 7 because that is the max between the 3 
//integers.
}

更新C++17现在定义了一个函数std::size,可以返回数组的大小。

#include <iostream>
#include <iterator>
using namespace std;
int findMaxRec(const int[] A, const int &n)
{
if (n <= 0) throw "error: array is empty...";
if (n == 1) return A[0];
return std::max(A[n - 1], findMaxRec(A, (n - 1)));
}
int findMaxRec(const int[] A)
{
return findMaxRec(A, std::size(A));
}
const int& findMaxRec(const int &i)
{
return i;
}

如果您没有 C++17,您会考虑使用列表吗?

#include <algorithm>
#include <list>
int findMaxRec(const std::list<int> &L)
{
if (L.size() == 0) throw "error: list is empty...";
return (*std::max_element(L.begin(), L.end()));
}

findMaxBetwen可以作为函数模板实现:

template<typename T> int findMaxBetwen(const T &data, int low, int high)
{
int i = findMaxRec(data);
if (i <= low) return low;
if (i >= high) return high;
return i;
}
//....
int main(int argc, char** argv)
{
std::list<int> a = {5, 6, 7, 8, 10};
cout << findMaxBetween(a, 5, 8) << 'n'; // output is 8
int b[5] = {5, 6, 7, 8, 10};
cout << findMaxBetween(b, 5, 8) << 'n'; // output is 8
int c = 7;
cout << findMaxBetween(c, 5, 8) << 'n'; // output is 7
}

在 cpp 首选项中了解有关函数模板的详细信息