概述
I am trying to use recursion to find the maximum value in an array in JavaScript. I created the function, but cannot figure out how to do it recursively.
function Max(a) {
var a = [2,3,5];
return Math.max.apply(Math, a);
}
解决方案
Here is an example of a recursive function that takes an array of numbers and compares the first two, removes the lesser, and then calls itself again on the given array minus the removed number.
function max(numArray)
{
// copy the given array
nums = numArray.slice();
// base case: if we're at the last number, return it
if (nums.length == 1) { return nums[0]; }
// check the first two numbers in the array and remove the lesser
if (nums[0] < nums[1]) { nums.splice(0,1); }
else { nums.splice(1,1); }
// with one less number in the array, call the same function
return max(nums);
}
最后
以上就是明亮黑裤为你收集整理的java 递归求解数组中的最大值,递归查找数组中的最大值的全部内容,希望文章能够帮你解决java 递归求解数组中的最大值,递归查找数组中的最大值所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复