Finding the minimum of an array using recursion?

我们两清 提交于 2021-02-04 15:28:45

问题


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:

I'm trying to find the minimum number in an array using recursion but keep getting an answer of 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

回答1:


There are a variety of problems in this code including:

  • You don't use the result of the recursive findMin call.
  • startIndex will be the same for every call to findMin, because currentIndex is being set to the value of startIndex before startIndex is incremented.
  • If the number at index 1 in the array is <= the number at index 0, you just return that number without even making the recursive call.



回答2:


Hint: You're calling findMin recursively, but then not using its return value.

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?




回答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;
}



回答4:


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 - i.e. 'findMin(numbers, currentIndex+1, endIndex)'


来源:https://stackoverflow.com/questions/5601232/finding-the-minimum-of-an-array-using-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!