Kevin
Kevin

Reputation: 6833

Find the maximum elements in an array using recursion

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!

Upvotes: 1

Views: 1059

Answers (1)

Lrrr
Lrrr

Reputation: 4817

First of all what n.m said is right, copying array is expensive and unnecessary. the other algorithm use start to avoid this.

but for your question. you actually use largest just didnot name it any thing!

return findMax(Arrays.copyOf(arr, arr.length-1))> arr[arr.length-1]?findMax(Arrays.copyOf(arr, arr.length-1)):arr[arr.length-1];

is where you find largest. it is exactly like another algorithm you mentioned. first of all you find the largest in : findMax(Arrays.copyOf(arr, arr.length-1)) and then you compare its value with : arr[arr.length-1] choose whatever is larger to be you current largest.

another advice, why you need to call findMax(Arrays.copyOf(arr, arr.length-1)) two time? simply use a variable to enhance you algorithm speed.

Upvotes: 3

Related Questions