Recursion - Get maximum from array

I am having trouble getting program to return the largest number in an

Page 1 of 1

1 Replies - 5833 Views - Last Post: 01 April 2009 - 11:02 PM Rate Topic: -----

#1 nanoo51969  Icon User is offline

  • New D.I.C Head

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

Recursion - Get maximum from array

Post icon  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  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • 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];}
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1