简体   繁体   中英

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}; and I search from index 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. 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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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