使用递归查找数组中的最大元素 [英] Find the maximum elements in an array using recursion

查看:205
本文介绍了使用递归查找数组中的最大元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是算法初学者。我刚刚制定了一个递归地找到整数数组中的最大元素的解决方案:

I am a algorithm beginner.I just worked out a solution to "recursively find the maximum elements in an array of integers":

public static int findMax(int[]arr)
{

  if(arr.length==1)
    return arr[0];

  return findMax(Arrays.copyOf(arr, arr.length-1))> arr[arr.length-1]?findMax(Arrays.copyOf(arr, arr.length-1)):arr[arr.length-1];
}

我做了几次测试,看来工作正常。

I did test several times, it seems to work correctly.

但是,我发现有人也使用其他递归方法来解决它,就像这篇文章一样:

However, I found someone used other recursion methods solved it too like in this post:

使用递归java在数组中查找最大值

他的代码如下:

 int largest(int[] a, int start, int largest) 
 {
   if (start == a.length)
     return largest;
   else {
    int l = (a[start] > largest ? a[start] : largest);
    return largest(a, start + 1, l);
}

我被困在这方面的思维方式差异的本质问题。我的想法是:

I am stuck here on the essence of difference in our thinking style for this particular problem.My thoughts is like:

1.he在每次递归中使用了另一个参数 start来跟踪当前光标到数组元素,我没有使用该参数,因为我在每次递归中都将数组缩小1,并始终使用tail元素进行比较;

1.he used another parameter "start" to keep track of the current cursor to the array element in every recursion, I didn't use that since I shrink the array by 1 in every recursion and always use the tail element to compare;

2。他使用了另一个参数 largest来跟踪到目前为止找到的最大值。我没有在代码中使用它,但是没有使用。这实际上就是我遇到的问题。我没有使用该最大变量来跟踪每次迭代中的最大值,为什么我可以获得相同的结果?

2.he used another parameter "largest" to keep track of the maximum value found so far. I didn't use this in my code, but I didn't use that. And this is actually where I get stuck. I didn't use that "largest" variable to keep track of the maximum in each iteration, why could I achieve the same result?

任何帮助都将不胜感激!

Any help is greatly appreciated!

推荐答案

首先,nm所说的是正确的,复制数组既昂贵又不必要。

First of all what n.m said is right, copying array is expensive and unnecessary. the other algorithm use start to avoid this.

但是对于您的问题。您实际上使用的是最大的,只是什么都没说!

but for your question. you actually use largest just didnot name it any thing!

return findMax(Arrays.copyOf(arr, arr.length-1))> arr[arr.length-1]?findMax(Arrays.copyOf(arr, arr.length-1)):arr[arr.length-1];

是您找到的最大的地方。就像您提到的另一种算法一样。首先,您在以下位置找到最大的值: findMax(Arrays.copyOf(arr,arr.length-1)),然后将其值与以下内容进行比较: arr [arr.length-1] 选择较大的值,使其成为当前最大的值。

is where you find largest. it is exactly like another algorithm you mentioned. first of all you find the largest in : findMax(Arrays.copyOf(arr, arr.length-1)) and then you compare its value with : arr[arr.length-1] choose whatever is larger to be you current largest.

另一个建议,为什么需要致电 findMax(Arrays.copyOf(arr,arr.length-1))两次?只需使用变量来提高算法速度。

another advice, why you need to call findMax(Arrays.copyOf(arr, arr.length-1)) two time? simply use a variable to enhance you algorithm speed.

这篇关于使用递归查找数组中的最大元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆