1. Member
Join Date
Feb 2011
Posts
43
Rep Power
0

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!?

Java 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;
}```

2. 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.

3. Member
Join Date
Feb 2011
Posts
43
Rep Power
0
Pass the number found you say. All right, the code definitely gets easier to read. Any other things on the pro list?

4. use a for-each loop instead?

finding the largest int:
Java Code:
```int largestInt = intArray[0];
for (int nextInt:intArray) {
if (largestInt < nextInt) {
largestInt = nextInt;
}
}```

5. Member
Join Date
Feb 2011
Posts
43
Rep Power
0
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. :)

6. 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.

7. Member
Join Date
Feb 2011
Posts
43
Rep Power
0
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!

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•