Monday, December 12, 2011

Recursive method to find maximum double (binary search style)?

I need to write (in Java) a recursive method static double findMax(double[] elements, int startIndex, int endIndex) that, when given an array of doubles and an index of the array, finds the largest element in the list.





I have a general idea of how to do this modeling the binary search algorithm and merge sort algorithm (since these split the array into smaller and smaller chunks and compare values). My question is: how do I store the value of the maximum double found so far in the array? I don't have another argument in the method to work with. This would seem doable to me if I was writing static double findMax(double[] elements, int startIndex, int endIndex, double max). (Using a static variable is not an option.)





Any help?|||You don't give much of a clue as to what startIndex and endIndex represent, however I believe the solution you want is something like the following:





static double findMax(double[] elements, int startIndex, int endIndex)


{


if (startIndex + 1 == endIndex) {


return elements[startIndex];


}


else {


double head = elements[startIndex];


double tailMax = findMax(elements, startIndex + 1, endIndex);


if (head %26lt; tailMax) {


return tailMax;


} else {


return head;


}


}

No comments:

Post a Comment