MaxArrayElement.java

Download
1/*2 * MaxArrayElement.java3 *4 * Computer Science E-22/S-225 *6 * A class that contains a recursive method for finding the 7 * maximum value in an array of integers.8 * 9 * The main method includes two examples of using this method.10 */11 12public class MaxArrayElement {13    /*14     * maxVal - determines the maximum element in the portion15     * of the array vals that begins at position start16     * 17     * assumptions: vals refers to an array with at least 1 integer18     *              start is a valid array index for vals19     */20    public static int maxVal(int[] vals, int start) {21        if (start == vals.length - 1) { // base case   22            return vals[start];23        } else {                        // recursive case24            int maxRest = maxVal(vals, start + 1);25            if (vals[start] > maxRest) {26                return vals[start];27            } else {28                return maxRest;29            }30        }31    }32 33    public static void main(String[] args) {34        int[] vals1 = {4, 8, 12, 3, 5};35        System.out.print("max value in entire array: ");36        System.out.println(maxVal(vals1, 0));37 38        System.out.print("max value in subarray beginning at posn 3: ");39        System.out.println(maxVal(vals1, 3));40    }41}