Results 1 to 7 of 7
Thread: Array - Recursive search.
- 03-27-2011, 11:24 AM #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; }
- 03-27-2011, 11:33 AM #2
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
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, 02:00 PM #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?
-
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; } }
- 03-27-2011, 02:55 PM #5
Member
- Join Date
- Feb 2011
- Posts
- 43
- Rep Power
- 0
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, 07:19 PM #6
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
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-27-2011, 11:55 PM #7
Member
- Join Date
- Feb 2011
- Posts
- 43
- Rep Power
- 0
Similar Threads
-
Array out of bound- Recursive Method
By hpayandah in forum New To JavaReplies: 2Last Post: 11-12-2010, 08:02 PM -
Recursive method using int array, help needed
By chupalo17 in forum New To JavaReplies: 4Last Post: 09-07-2009, 11:15 PM -
Recursive Binary Search
By EternalSolitude in forum New To JavaReplies: 2Last Post: 11-21-2008, 06:26 AM -
Recursive Method ==> find minimum value from array
By NatNat in forum New To JavaReplies: 1Last Post: 02-16-2008, 09:10 PM -
problem with recursive binary search program
By imran_khan in forum New To JavaReplies: 3Last Post: 08-02-2007, 03:08 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks