Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 269
Vance Avatar asked Apr 08 '11 22:04

Vance


People also ask

How do you find the minimum of an array?

M = min( A ) returns the minimum elements of an array. If A is a vector, then min(A) returns the minimum of A . If A is a matrix, then min(A) is a row vector containing the minimum value of each column of A .


2 Answers

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?

like image 118
Gareth McCaughan Avatar answered Oct 15 '22 21:10

Gareth McCaughan


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;
}
like image 5
Abel Perez Avatar answered Oct 15 '22 20:10

Abel Perez