The Artima Developer Community
Sponsored Link

Java Answers Forum
searching array using recursion

2 replies on 1 page. Most recent reply: Oct 30, 2004 12:55 AM by Matthias Neumair

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Andrew Holmes

Posts: 1
Nickname: baconsoft
Registered: Oct, 2004

searching array using recursion Posted: Oct 29, 2004 6:05 AM
Reply to this message Reply
Advertisement
Hi there
I dont know if this is the right forum to be asking novice questions but anyway, here goes.

I am trying to complete a problem which I have been trying to solve for ages but I cannot get it to work.

Q. Using recursion, find the largest value in the array

public class DataSet
{

.....
public Dataset (int[] anArray) {.......}
public int getMaximum () {.....}
......

}

If anyone could provide me with pseudocode or code to solve this one it would be very much appreciated. I have been trying but I cant do it.

Thanks again
Baconsoft


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: searching array using recursion Posted: Oct 29, 2004 11:58 AM
Reply to this message Reply
For a recursion you need a stop condition.

To find a stop condition you need an input value.

Using recursion on an array only to find the biggest value sounds kinda sensless to me, but here we go: Just transform the array into a Vector.

Here's your solution:

public int getMaximum () {
Vector v = new Vector();
for (int i = 0; i < anArray; i++)
v.add(new Integer(anArray[i]);
if (v.size() > 0)
return getMaximum (v);
return -9999999999;
}
private int getMaximum (Vector v) {
int val = (Integer)v.get(0);
v.removeElementAt(0);
return (v.size() <= 0)? val : Math.max (val, getMaximum (Vector v));
}


I know this looks stupid, but it's one way to do it.

Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: searching array using recursion Posted: Oct 30, 2004 12:55 AM
Reply to this message Reply
I made an error.
Should be

int val = ((Integer)v.get(0)).intValue();

Flat View: This topic has 2 replies on 1 page
Topic: Date util function Previous Topic   Next Topic Topic: faq's in java

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use