# Array - Recursive search.

• 03-27-2011, 12:24 PM
überfuzz
Array - Recursive search.
Is it possible to search an array for, lets say the biggest (int), without passing the index? I can't think of any way, but if anyone has a nifty trick!?

Code:

```  public static int arrayMax(int i, int[] array)   {       if(i == array.length-1)    //i can be used as an offset.       {         return array[i];       }       int temp = arrayMax(i+1, array);    //next index.       if(array[i] > temp)       {         return array[i];       }       return temp;   }```
• 03-27-2011, 12:33 PM
sunde887
There is a way, you should consider having the method take 3 arguments, 1 which is the index, one which is the array and one that's the largest number.
The termination condition is if index == array.length.

With that in mind, give it a shot and post up your attempt.
• 03-27-2011, 03:00 PM
überfuzz
Pass the number found you say. All right, the code definitely gets easier to read. Any other things on the pro list?
• 03-27-2011, 03:19 PM
ozzyman

finding the largest int:
Code:

```int largestInt = intArray[0]; for (int nextInt:intArray) {     if (largestInt < nextInt) {         largestInt = nextInt;     } }```
• 03-27-2011, 03:55 PM
überfuzz
Quote:

Originally Posted by ozzyman
...
[code]for (int nextInt:intArray)

Normally I would use a for loop, but this was a school exercise in which I was supposed to use a recursive function. Further, I was to use arrayMax(index, array[]) as params. (We're testing execute time comparing loops and recursive functions.) However, thanks for the for syntax. New to me. :)
• 03-27-2011, 08:19 PM
sunde887
What have you tried using a 3rd variable? The index should change each recursive pass, and the max variable should only change sometimes. Show your attempts, and Ill let you know where you went right/wrong.
• 03-28-2011, 12:55 AM
überfuzz
Quote:

Originally Posted by sunde887
Show your attempts, and Ill let you know where you went right/wrong.

See the first post in this thread. It seems to work like a charm. Cheers!