Source of ArrayMax.java


  1: 
  2: import java.util.ArrayList;
  3: import java.util.List;
  4: import java.util.Random;
  5: 
  6: /**
  7:  * Find the maximum value in a List. RECURSIVELY.
  8:  *
  9:  * NOTE: Recursively is a silly way to do this, but it's an exercise in thinking
 10:  * recursively.
 11:  *
 12:  * @author Mark Young (A00000000)
 13:  */
 14: public class ArrayMax {
 15: 
 16:     /**
 17:      * @param args the command line arguments
 18:      */
 19:     public static void main(String[] args) {
 20:         List<Integer> numbers = generateRandomNumbers(10);
 21: 
 22:         System.out.println("The maximum value in " + numbers);
 23:         System.out.println("is " + getMax(numbers) + ".");
 24:     }
 25: 
 26:     /**
 27:      * Generate numElts random numbers in the range [0, 1000).
 28:      *
 29:      * @param numElts the number of elements in the result
 30:      * @return a list of random numbers
 31:      */
 32:     private static List<Integer> generateRandomNumbers(int numElts) {
 33:         List<Integer> result = new ArrayList<>();
 34:         Random rand = new Random();
 35: 
 36:         for (int i = 0; i < numElts; ++i) {
 37:             result.add(rand.nextInt(1000));
 38:         }
 39: 
 40:         return result;
 41:     }
 42: 
 43:     /**
 44:      * Find the maximum element of a List of Integer values.
 45:      *
 46:      * @param numbers the list of numbers
 47:      * @return the largest of those numbers
 48:      */
 49:     private static int getMax(List<Integer> numbers) {
 50:         return getMax(numbers, 0, numbers.size());
 51:     }
 52: 
 53:     /**
 54:      * Find the maximum element of part of a List of Integer values -- starting
 55:      * at index lo and continuing up to (but not including) index hi.
 56:      *
 57:      * PRECONDITION: lo &lt; hi AND 0 &le; lo &lt; hi AND hi &le; numbers.size()
 58:      *
 59:      * @param numbers the list of numbers
 60:      * @return the largest of those numbers
 61:      */
 62:     private static int getMax(List<Integer> numbers, int lo, int hi) {
 63:         if (hi - lo == 1) {
 64:             return numbers.get(lo);
 65:         } else {
 66:             return Math.max(numbers.get(lo), getMax(numbers, lo+1, hi));
 67: 
 68:             /* OR */
 69:             // return Math.max(getMax(numbers, lo, hi-1), numbers.get(hi-1));
 70:         }
 71:     }
 72: 
 73: }