gpt4 book ai didi

java - 递归方法寻找最小整数?

转载 作者:行者123 更新时间:2023-11-30 03:27:25 25 4
gpt4 key购买 nike

所以我有一个作业,我必须创建一个接受 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

关于java - 递归方法寻找最小整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29855114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com