So I've got an assignment where I have to create a method which takes an int[] parameter and returns the smallest int. There's only one problem though...we have to use recursion! Anyway, here is my code:
static int[] arr = {12, 8, 4, 17};
public static void main(String[] args){
System.out.println("Minimum is :" + findMin(arr));
}
public static int findMin(int[] iArray){
if(arr.length == 0) {
System.err.println("Please Pass An Array With At Least 1 Element.");
return (Integer) null;
}
else return findMinFromArray(iArray, 0, iArray[0]); //call method with starting parameters ie index = 0 & min = iArray[0]
}
private static int findMinFromArray(int[] iArray, int index, int min) {
if(index <= (iArray.length - 1)){
if(iArray[index] < min){
min = iArray[index];
}
System.out.println("Before: " + "Index = " + index + " | Min = " + min);
findMinFromArray(iArray, index + 1, min);
}
System.out.println("After: " + "Index = " + index + " | Min = " + min);
return min;
}
And here is the output...
Before: Index = 0 | Min = 12
Before: Index = 1 | Min = 8
Before: Index = 2 | Min = 4
Before: Index = 3 | Min = 4
After: Index = 4 | Min = 4
After: Index = 3 | Min = 4
After: Index = 2 | Min = 4
After: Index = 1 | Min = 8
After: Index = 0 | Min = 12
Minimum is :12
So as you can see, the code is kind of working, but I'm not sure how to get the program to stop, rather than going back again like it's doing.