Finding Max value in an array using recursion

You could just as easily do it with only one counter, just the index of the value you want to compare this time:

public static int findMax(int[] a, int index) {
    if (index > 0) {
        return Math.max(a[index], findMax(a, index-1))
    } else {
        return a[0];
    }
}

This much better shows what is going on, and uses the default “recursion” layout, e.g. with a common base step. Initial call is by doing findMax(a, a.length-1).

Leave a Comment