使用递归查找数组c ++的最大值和最小值而无需更改函数 [英] find max and min of array c++ using recursion without changing function
本文介绍了使用递归查找数组c ++的最大值和最小值而无需更改函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助,尝试在c ++中递归地在数组中查找最小值和最大值.功能已给出,无法更改.
I need help trying to find the min and max values in an array recursively in c++. the functions were given and cannot be changed.
我都尝试过,但是由于某种原因什么也没发生,并且代码没有进入循环,我想知道自己在做什么错.这是我的主要功能以及最小和最大功能.
I tried it out for both but for some reason nothing happens and the code does not enter the loop and I want to know what I am doing wrong. Here is my main and the min and max functions.
int main()
{
int array[] = { 46, 22, 7, 58, 91, 55, 31, 84, 12, 78 };
if (findMax(array, 10) == 91)
{
cout << "findMax is correct!" << endl;
}
if (findMin(array, 10) == 7)
{
cout << "findMin is correct!" << endl;
}
int findMax(int array[], int size)
{
int i = (size - 1);
int max = 0;
if (array[0] < array[i]) {
max = array[i];
findMax(array, size - 1);
}
return max;
return 0;
}
int findMin(int array[], int size)
{
int i = 0;
int j = size - 1;
if (i == j)
{
return array[i];
i++;
}
int temp = findMin(array, size);
if (array[i] < temp)
{
return array[i];
}
else
{
return temp;
}
}
}
推荐答案
好吧,您只需向后移动,返回每对元素的最小值,然后再进行下一级别将数组大小减小一倍.示例:
Well, you simply go backwards, return the min of each pair of elements and then next level make array size one smaller. Example:
int findMin(int array[], int n)
{
// if size = 0 means whole array has been traversed
if (n == 1){
return array[0];
}
return min(array[n-1], findMin(array, n-1));
}
您可以使用相同的方法进行 findMax
.
And you can do the findMax
using the same methodology.
这篇关于使用递归查找数组c ++的最大值和最小值而无需更改函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文