I am a algorithm beginner.I just worked out a solution to "recursively find the maximum elements in an array of integers":
public static int findMax(int[]arr)
{
if(arr.length==1)
return arr[0];
return findMax(Arrays.copyOf(arr, arr.length-1))> arr[arr.length-1]?findMax(Arrays.copyOf(arr, arr.length-1)):arr[arr.length-1];
}
I did test several times, it seems to work correctly.
However, I found someone used other recursion methods solved it too like in this post:
finding max value in an array using recursion java
His code is like:
int largest(int[] a, int start, int largest)
{
if (start == a.length)
return largest;
else {
int l = (a[start] > largest ? a[start] : largest);
return largest(a, start + 1, l);
}
I am stuck here on the essence of difference in our thinking style for this particular problem.My thoughts is like:
1.he used another parameter "start" to keep track of the current cursor to the array element in every recursion, I didn't use that since I shrink the array by 1 in every recursion and always use the tail element to compare;
2.he used another parameter "largest" to keep track of the maximum value found so far. I didn't use this in my code, but I didn't use that. And this is actually where I get stuck. I didn't use that "largest" variable to keep track of the maximum in each iteration, why could I achieve the same result?
Any help is greatly appreciated!