简体   繁体   English

递归函数如何查找数组的最小元素?

[英]How does a recursive function to find the minimum element of an array work?

I have this method about finding the minimum of an array using recursion, which I'm learning about right now. 我有这种使用递归查找数组最小值的方法,我现在正在学习。

public class findMin {
    private static int findMin(int[] data, int index) {
    int min;
    if (index == data.length - 1)//base case
    return data[index];
    min = findMin(data, index + 1);
    if (min < data[index])
    return  min;
    else
    return data[index];

    } 
}

For example, my array is int[] numbers = {3, 15, 1, 9, 6, 12, 21, 17, 4}; 例如,我的数组是int[] numbers = {3, 15, 1, 9, 6, 12, 21, 17, 4}; and I search from index 0. 然后从索引0开始搜索

My question is how does the method go throw the whole array? 我的问题是该方法如何抛出整个数组? I can see that it checks but shouldn't it be in a loop to go throw the whole array? 我可以看到它检查了一下,但不是应该循环抛出整个数组吗?

You have two options you are talking about 您正在谈论两种选择

  • use a loop to go through an array. 使用循环遍历数组。
  • use recursion in a way which visits each element of an array without using a loop. 使用递归的方式访问数组的每个元素而无需使用循环。

When you use a loop you have something like 使用循环时,您会遇到类似

{initial data}
for({initial state} ; {stop condition} ; {incrementation} }

When you use recursion you do something like. 使用递归时,您会执行类似的操作。

// call the function the first time
method({initial data}, {initial state});


// inside the method it checks the condition
if ({condition})
     return {result}
else
     method({data}, {incrementation});

And if you think that makes recursion look needlessly complicated and inefficient, this is because Java is based on procedural languages which preferred loops and is not a functional language. 而且,如果您认为使递归看起来不必要地复杂且效率低下,那是因为Java基于过程语言,后者倾向于循环,而不是功能语言。 In functional language it is often the case that recursion is more elegant and loops are relatively hard. 在函数式语言中,通常情况下递归更为优雅,而循环则相对困难。

my question is how does the mehod go throw the whole array? 我的问题是方法如何抛出整个数组?

each time the method calls itself it increments the index and there is a condition check to stop at the end. 每次该方法自身调用时,它都会递增索引,并且条件检查会在最后停止。

i can see that it check but its shouldnt it be in a loop to go throw the whole araay? 我可以看到它检查但它不应该处于循环中以抛出整个araay吗?

I wouldn't assume that loops are the only way to solve a problem. 我不认为循环是解决问题的唯一方法。

Note: when recursion is supported efficiently, tail-recursion optimisation can turn recursion into a loop. 注意:当有效支持递归时,尾递归优化可以将递归变成一个循环。 The JVM doesn't have this optimisation unfortunately. 不幸的是,JVM没有这种优化。

In the line 在行中

min = findMin(data, index + 1);

the method calls itself. 该方法会自行调用。 This makes the method essentially loop through the array, because each time the method calls itself, it increases the index by one. 这使得该方法实质上遍历了数组,因为每次该方法自身调用时,索引都会增加一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM