Using recursion, find the largest element in an array.
public class DataSet
{
public DataSet(int[] values, int first, int last) { . . . }
public int getMaximum() { . . . }
. . .
}
Hint: Find the largest element in the subset containing all but the last element. Then compare that maximum to the value of the last element.
Used the following class as your tester class:
import java.util.Random;
/**
A tester class for the recursive maximum.
*/
public class DataSetTester
{
public static void main(String[] args)
{
int[] values = { 1, 10, 100, -1, -10, -100, 100, 0 };
DataSet d = new DataSet(values, 0, values.length - 1);
System.out.println("Maximum: " + d.getMaximum());
System.out.println("Expected: 100");
}
}
//SOLUTION:
/**
Computes the maximum of a set of data values.
*/
public class DataSet
{
/**
Constructs a DataSet object.
@param values the data values
@param first the first value in the data set
@param last the last value in the data set
*/
public DataSet(int[] values, int first, int last)
{
this.values = values;
this.first = first;
this.last = last;
}
/**
Gets the maximum in the set of data values
@return the maximum value in the set
*/
public int getMaximum()
{
if (first > last)
return Integer.MIN_VALUE;
DataSet tail = new DataSet(values, first + 1, last);
int tailMax = tail.getMaximum();
return Math.max(values[first], tailMax);
}
private int[] values;
private int first;
private int last;
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment