I have an assignment on recursion that calls for me to use recursion to find the largest element in an array. I have a general understanding on how recursion works but this problem throws me off because I can't figure out how to correctly implement the getMaximum() function which is suppose to keep calling itself to find the largest element. I kinda have an idea on the special case which causing the recursion to terminate but that's about it. Any help would be appreciated.

/**
   Computes the maximum of a set of data values.
*/
public class DataSet
{
   private int[] values;
   private int first;
   private int last;

   /**
      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()
   { 
   }
   
}

Tester supplied by my instructor:

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");
   }
}

What are the restrictions on the code that can be written to solve this?

The restrictions are that you must use a recursive method to come up with the getMaximum method. Cannot use a iterative solution. Still stuck on this one.

If there are no restrictions on the variables that the DataSet class can have,
Add some more variables that your recursive method can use to walk through the array and remember the max value seen so far.

Oh no I'm sorry I see what you mean. No I don't think you can add variables and change the interface of the class. Everything has to be done within the getMaximum method.

If you can not change the contents of the DataSet class and can only add code to the getMaximum method, I do NOT see any way to solve the problem.
You need a way to keep track of which elements you have looked at and what was the maximum value found.
The local variables in the getMaximum method can not do that. How would you tell the the method what the max value that was found so far and where to continue looking to get through the rest of the array?
The only solution I see is to add more variables to the DataSet class to keep track.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.