[英]Finding Max of an array using Recursion
So it's pretty simple to find the max of an array using a for loop or a while loop, but I wanted to try it out with recursion. 因此,使用for循环或while循环查找数组的最大值非常简单,但我想通过递归进行尝试。 For some reason, the substring doesn't work - it says "cannot find symbol". 由于某种原因,子字符串不起作用-它说“找不到符号”。 Why is this? 为什么是这样? My strategy is continue subdividing and comparing the two sides until there is only one left which should be the max....am I doing it right? 我的策略是继续细分并比较这两个方面,直到只剩下一个应该是最大数量为止。...我做对了吗? Thanks 谢谢
public static int max(int[] array) {
if (array.length == 1) {
return array[0];
} else {
int mid = (array.length) / 2;
int leftmax = max(array.substring(0, mid));
int rightmax = max(array.substring(mid, array.length));
if (leftmax > rightmax) {
return leftmax;
} else {
return rightmax;
}
}
}
You are going to want to use Arrays.copyOfRange
. 您将要使用Arrays.copyOfRange
。 Substring
isn't going to work on an array. Substring
在数组上不起作用。
int[] firstHalf = Arrays.copyOfRange(original, 0, original.length/2);
int[] secondHalf = Arrays.copyOfRange(original, original.length/2, original.length);
I can't comment on your algorithm. 我无法评论您的算法。
Since array
is of type int[]
not String
, you cannot use substring()
. 由于array
类型为int[]
而不是String
,因此不能使用substring()
。 Instead, keep track of which indexes you are searching through. 相反,请跟踪正在搜索的索引。 Copying the array each iteration is a waste of both space and time. 在每次迭代中复制数组都浪费了空间和时间。
int max( int[] array ){ return max( array, 0, array.length - 1 ); }
int max( int[] array, int low, int high )
{
if (low == high) {
return array[low];
}
else {
int mid = (high + low) / 2;
int leftmax = max(array, low, mid );
int rightmax = max(array, mid, high );
if (leftmax > rightmax) {
return leftmax;
}
else {
return rightmax;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.