Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

Recursive function that finds the minimum value in an ArrayList of Integers in Java

This is a problem that I have been thinking about as part of self-learning java. The problem consists of writing a recursive function that finds the minimum value in an ArrayList of Integers. Below you will find my attempt. I believe that it is working as intended, but I wonder if there are better ways to get this done. Any comments are appreciated.

public static int findMin(ArrayList<Integer> numbers){
        // Base Case
        if(numbers.size()==1){
            return numbers.get(0).intValue();
        }
    
  
        ArrayList<Integer> numbers_short = new ArrayList<Integer>(numbers);
        numbers.remove(numbers.size()-1);

        return Math.min(numbers_short.get(numbers_short.size()-1).intValue(), findMin(numbers));
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your example is not so good in the way that you should not use recursivity in this case. But anyway, you can avoid to copy your array each time, by using a method with a start and end parameters to analyze only a part of your initial array.

Something like that:


    public static int findMin(ArrayList<Integer> numbers) {
        return findMin(numbers, 0, numbers.size() - 1);
    }

    public static int findMin(ArrayList<Integer> numbers, int start, int end) {
        if (end == start)
            return numbers.get(start);
        int middle = start + (end - start) / 2;
        return Math.min(findMin(numbers, start, middle), findMin(numbers, middle + 1, end));
    }

And add a check in case the array is empty if needed.

The reason why I'm using the "middle" method is that each time it divides the array by 2, meaning at the end it limits the risk of stack overflow because it will divide by 2 the maximum number of recursivity compare to recurse on every element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...