# Recursion - Get maximum from array

Page 1 of 1

## 1 Replies - 8336 Views - Last Post: 01 April 2009 - 11:02 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=96810&amp;s=131abd8d805f2b849b7c6f583d864e25&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 nanoo51969

Reputation: 0
• Posts: 6
• Joined: 23-March 09

# Recursion - Get maximum from array

Posted 01 April 2009 - 09:56 PM

The assignment is to find the largest element in an array.
Book gives hint: find the largest element in the subset containing all but last element, then compare maximum to the value of the last element. Our instructor said we could also just compare ea element. either way this is not working. Can anyone help?
[code]
public class DataSet
{
public DataSet()
{
largest = 0;
}
public int theLargest(int[]a, int start, int end)
{
if(start == end)
return largest = a[start];
int first = a[start];
int next = theLargest(a, start+1, end);
if(first > next)
return largest = first;
else return largest = next;
}
public int getLargest()
{
return largest;
}
private int largest;
}

public class Main
{

public static void main(String[] args)
{
DataSet myData = new DataSet();
int[] a = {5, 12, 32, 8, 9}; //Generate an array of 5 elements.

System.out.println("Elements of array[]: ");
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println("\nLargest element in array[]: ");
System.out.println(myData.getLargest());

} //end of main()
}//end of class

Is This A Good Question/Topic? 0

## Replies To: Recursion - Get maximum from array

### #2 Fuzzyness

• Comp Sci Student

Reputation: 669
• Posts: 2,438
• Joined: 06-March 09

## Re: Recursion - Get maximum from array

Posted 01 April 2009 - 11:02 PM

int largest = a[0];
for(int i = 0; i<a.length;i++)
{if(a[i] > largest)
largest = a[i];}