This question already has answers here:
Java: Recursively Finding the minimum element in a list
(5个答案)
4年前关闭。
因此,我要完成一个任务,其中我必须创建一个使用int []参数并返回最小int的方法。不过,只有一个问题...我们必须使用递归!无论如何,这是我的代码:
这是输出...
如您所见,代码可以正常工作,但是我不确定如何停止程序,而不是像执行操作那样再次返回。
至
完整的固定方法:
输出:
(5个答案)
4年前关闭。
因此,我要完成一个任务,其中我必须创建一个使用int []参数并返回最小int的方法。不过,只有一个问题...我们必须使用递归!无论如何,这是我的代码:
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;
}
这是输出...
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
如您所见,代码可以正常工作,但是我不确定如何停止程序,而不是像执行操作那样再次返回。
最佳答案
您的错误是忽略了递归调用的结果。
更改
findMinFromArray(iArray, index + 1, min);
至
return findMinFromArray(iArray, index + 1, min);
完整的固定方法:
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);
return findMinFromArray(iArray, index + 1, min);
}
System.out.println("After: " + "Index = " + index + " | Min = " + min);
return min;
}
输出:
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