简体   繁体   中英

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:

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

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?

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:

  • 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.

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)'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM