我试图通过做一些代码来理解递归。此代码应以递归方式查找数组中的最大数字,但由于某种原因,它不起作用。 谢谢你的帮助!
public static void main(String[] args) {
int array [] = {11,4,6,9,15,2};
maxNum(array, 1, 0);
}//Main
public static int maxNum(int array[], int maxIndex, int i)
{
int ans;
if(i==array.length-1) //Condition Stop
{
ans= maxIndex;
}
else
{
ans= maxNum(array, Math.max(array[maxIndex], array[i]), i++);
}
System.out.println(array[maxIndex]);
return ans;
}//maxNum
}//Class
答案 0 :(得分:1)
我发现位Math.max(array[maxIndex], array[i])
有问题。您使用此作为递归调用maxNum()
的第二个参数,但您从数组中获得值,而不是索引。换句话说,你最终会使用数组中的11或15之类的值作为索引。
答案 1 :(得分:1)
public static void main(String[] args) {
int array [] = {11,4,6,9,15,2};
System.out.println(maxNum(array, 0, 1));
}//Main
public static int maxNum(int array[], int maxIndex, int i)
{
int ans;
if(i==array.length) //Condition Stop
ans=maxIndex;
else
ans=maxNum(array, (array[maxIndex]<array[i])?i:maxIndex, ++i);
return ans;
}//maxNum
}//Class
两个修改:i ++ - &gt; ++ i和Math.max(array [maxIndex],array [i]) - &GT; (阵列[maxIndex]
答案 2 :(得分:0)
此行存在问题:
ans= maxNum(array, Math.max(array[maxIndex], array[i]), i++);
第二个参数需要一个数组索引。但是,您使用数组值调用它:
Math.max(array[maxIndex], array[i])
返回数组中的值而不是索引。
即使你修复了这个问题,这里的递归也没有增加值。递归调用只是查找数组中的下一个值。你所做的只是迭代数组
但是,如果你构建了findMax函数来遵循这样的逻辑:
递归感觉不那么肤浅
答案 3 :(得分:0)
在这行代码第一次你做一些合法的事情,试图访问数组中存在的索引。但是下一次迭代你将11作为索引传递,因为你发现这个值是最大值,改变你的逻辑。
ans=maxNum(array, (array[maxIndex]<array[i])?i:maxIndex, ++i);
这个11索引不存在于数组中,因此您收到此错误。下一次您可以尝试通过IDE调试代码。此代码仅需要调试。
答案 4 :(得分:0)
您可以使用以下代码:
public static main(String ar[]){
int array [] = {11,4,6,9,15,2};
System.out.println(array[maxNum(array, 0, 0)]);
}
public static int maxNum(int array[], int maxIndex, int i)
{
int ans=0;
if(i==array.length-1) {
ans= maxIndex;
}
else {
ans= maxNum(array, (Math.max(array[maxIndex], array[i])==array[maxIndex])?maxIndex:i, ++i);
}
return ans;
}
您的代码出现问题:
maxNum
调用是传递值而不是索引。
++i
和i++
不同。
在函数调用中,如果要传递递增的i
值,请使用++i
。
答案 5 :(得分:0)
您的代码的问题是Math.max()返回值11,并且您尝试将其作为maxIndex传递给第二次调用maxNum。这导致尝试在下一次调用中访问数组[11],这显然不存在,代码导致ArrayOutOfBoundsException
。另一个问题是你正在使用i的后增量,这意味着,在将值传递给maxNum之后,i值将始终递增。你应该把它改成++ i。
而不是maxNum(array, Math.max(array[maxIndex], array[i]), i++);
使用
maxNum(array, array[maxIndex]>array[i]?maxIndex:i, ++i);
上面的代码会将maxIndex或i传递给下一个调用,在第一次递归调用maxNum时,调用将为0或1。
此代码不能解决您的所有代码问题。您正在打印array[maxIndex]
,这可能导致打印多次。我会留给你修理。
答案 6 :(得分:0)
在这行Math.max(array [maxIndex],array [i])中,你应该返回下一个索引而不是找到的最大值。如果您返回最大值,则不会按照我的假设进行配对比较。
答案 7 :(得分:0)
递归是一个复杂的主题。有一段时间试图用递归来解决每一个问题,这并不总是一个好主意。
就像许多已经指出的那样(@hasan,@ Buddha等),在提供的示例代码中,您将“数组中的值”与“数组中的索引”混合在一起。如果你已经在尝试理解递归,那么也可以重新访问数组。
好的方法是尝试简化代码,例如,您可以消除变量maxIndex
,并且只依赖于i
和i+1
。这将使您的代码不易出错,因为您需要考虑的事项较少。
答案 8 :(得分:0)
试试这个
public static void main(String[] args) {
int array [] = {11,4,6,9,15,2};
System.out.println(maxNum(array, array[0]));
}
public static int maxNum(int array[], int max)
{
if(array.length == 0)
return max;
return maxNum(Arrays.copyOfRange(array, 1, array.length), Math.max(array[0], max));
}