A recursive function that finds a minimum element in an array.

public class RecursiveMin {
    public static void main (String [] args) {
	int [] a = {4, 6, 3, 7, 2, 8};
	ArrayObj ao = new ArrayObj(a);
	System.out.println(ao.min());
    }
}

class ArrayObj {
    private int [] arr;

    public ArrayObj(int [] a) {
	// creating a local copy of the array
	arr = new int[a.length];
	for (int i = 0; i < a.length; ++i) {
	    arr[i] = a[i]; 
	}
    }

    public int min() {
	return minHelper(0);
    }

    private int minHelper (int index) {
	if (index == arr.length - 1) return arr[index];
	else {
	    int minTheRest = minHelper(index + 1);
	    if (arr[index] < minTheRest) 
		return arr[index];
	    else return minTheRest;
	}
    }
}

This is an example from CSci 1211 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.