[英]Finding the minimum of an array using recursion?
Ok, so I've been trying to wrap my head around recursion in Java and I can accomplish easy tasks such as sum, reversing etc. but I have been struggling to do this exercise:好的,所以我一直在尝试围绕 Java 中的递归进行思考,我可以完成简单的任务,例如求和、反转等。但是我一直在努力做这个练习:
I'm trying to find the minimum number in an array using recursion but keep getting an answer of 0.0.我正在尝试使用递归找到数组中的最小数,但一直得到 0.0 的答案。
My understanding for recursion is that there I need to increment one element and then provide a base case that will end the recursion.我对递归的理解是,我需要增加一个元素,然后提供一个基本情况来结束递归。 I think I'm messing up when I have to return a value and when is best to call the recursion method.我想当我必须返回一个值以及什么时候最好调用递归方法时,我就搞砸了。
This is what I have so far:这是我到目前为止:
public static double findMin(double[] numbers, int startIndex, int endIndex) {
double min;
int currentIndex = startIndex++;
if (startIndex == endIndex)
return numbers[startIndex];
else {
min = numbers[startIndex];
if (min > numbers[currentIndex]) {
min = numbers[currentIndex];
findMin(numbers, currentIndex, endIndex);
}
return min;
}
} //findMin
Hint: You're calling findMin
recursively, but then not using its return value.提示:您findMin
递归方式调用findMin
,但不使用其返回值。
What's the relationship between (1) the min of the whole array, (2) the first element, and (3) the min of everything apart from the first element? (1)整个数组的最小值,(2)第一个元素,以及(3)除了第一个元素之外的所有元素的最小值之间的关系是什么?
Here's a simplified version:这是一个简化版本:
public static double min(double[] elements, int index) {
if (index == elements.length - 1) {
return elements[index];
}
double val = min(elements, index + 1);
if (elements[index] < val)
return elements[index];
else
return val;
}
There are a variety of problems in this code including:这段代码有很多问题,包括:
findMin
call.您不使用递归findMin
调用的结果。startIndex
will be the same for every call to findMin
, because currentIndex
is being set to the value of startIndex
before startIndex
is incremented.每次调用findMin
startIndex
都相同,因为currentIndex
在startIndex
增加之前被设置为startIndex
的值。A few observations in addition to the first answer:除了第一个答案之外,还有一些观察:
int currentIndex = startIndex++;
- you're going to miss your first element here. - 你会在这里错过你的第一个元素。 In general, you don't want to modify the input to your recursive function.通常,您不想修改递归函数的输入。 Work off the input and generate new values when you're ready to call the function again - ie 'findMin(numbers, currentIndex+1, endIndex)'当您准备再次调用该函数时,处理输入并生成新值 - 即“findMin(numbers, currentIndex+1, endIndex)”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.