简体   繁体   English

用Java递归查找数组的最小值和最大值

[英]Recursively finding the min and max of an array with Java

So I'm trying to write a recursive algorithm which finds the min and max of an array. 所以我试图写一个递归算法来找到数组的最小值和最大值。 It basically splits the array into two n/2 pieces and finds the min and max recursively. 它基本上将数组分为两个n / 2片段,然后递归找到最小值和最大值。 Here's what I have right now: 这是我现在所拥有的:

class MinMax{
    public static Pair mmA(int lb, int ub, int[] a){
        int min;
        int max;
        int mid;
        if (ub == lb){
            return mmA(lb, ub, a);
        } else {
            mid = (lb + ub)/2;
            mmA (lb, mid, a);
            max = mid;
            mmA (mid+1, ub, a);
            min = mid;

            if (a[max] > a[min]){
                return mmA(lb, max, a);
            } else 
                return mmA(min, ub, a);
        }
    }

    public static void main(String[]args){
        int[] a = {4, 3, 5, 6, 7, 9, 1};
        mmA(0, 6, a);
    }
}

The problem is the method is not an int method so I can't just say max = mmA(lb, mid, a) because mmA is a Pair method while max is an int. 问题在于该方法不是int方法,因此我不能只说max = mmA(lb,mid,a),因为mmA是Pair方法,而max是int。 I also can't just make Max and Min pair objects because then you wouldn't be able to compare them at the end. 我也不能只制作Max和Min对对象,因为这样一来,您将无法在最后进行比较。 Here's the pair class: 这是配对类:

class Pair {
   int alpha;   // the smaller one 
   int omega; // the bigger one 
   Pair ( int a, int o ) { alpha = a; omega = o; }
}

So how can I use this pair class along with my method to find the min and max. 因此,如何使用此对类以及我的方法来找到最小值和最大值。

You can't. 你不能 Because, this function will end up in an end-less loop. 因为,此函数将以无限循环结束。

if (ub == lb){
    return mmA(lb, ub, a);
}

Let's say ub = lb = 5 . 假设ub = lb = 5 It will call mmA(5, 5, a) again. 它将再次调用mmA(5, 5, a) Which will in-turn call the same. 依次将调用相同。 And so on.. 等等..

EDIT: 编辑:

This should help, 这应该有帮助,

public class Main {
    public static Pair mmA(int lb, int ub, int[] a) {
        int min, max, mid;
        Pair p1, p2;

        if (ub == lb) {
            return new Pair(a[lb], a[ub]);
        } else {
            mid = (lb + ub) / 2;
            p1 = mmA(lb, mid, a);
            p2 = mmA(mid + 1, ub, a);

            max = Math.max(p1.omega, p2.omega);
            min = Math.min(p1.alpha, p2.alpha);

            return new Pair(min, max);
        }
    }


    public static void main(String[] args) {
        int[] a = {4, 3, 5, 6, 7, 9, 1};
        Pair pair = mmA(0, 6, a);
        System.out.println("Max = " + pair.omega + " & Min = " + pair.alpha);
    }
}


class Pair {
    public int alpha;
    public int omega;

    Pair(int a, int o) {
        alpha = a;
        omega = o;
    }
}

Since this seems to be an exercise in recursion, let me try to guide you under that pretext. 由于这似乎是递归练习,所以让我尝试以此为借口指导您。

Your recursive method returns a pair, being the min and max values. 您的递归方法返回一对,即最小值和最大值。 You call it twice, by splitting the array in two. 通过将数组一分为二,可以调用两次。 All good so far. 到目前为止一切都很好。

Now that you have two pairs (assuming you change code to actually assign return value to a variable), you just need to combine them. 现在您有了两对(假设您更改了代码以实际将返回值分配给变量),您只需要将它们组合即可。 Let's say your Pair class is immutable, then you could add a method to Pair like this: 假设您的Pair类是不可变的,那么您可以像这样向Pair添加一个方法:

public Pair combine(Pair other) {
    int newAlpha = Math.min(this.alpha, other.alpha);
    int newOmega = Math.max(this.omega, other.omega);
    return new Pair(newAlpha, newOmega);
}

NOTE: Be aware that your recursion stop logic doesn't work, as described in answer by Msp . 注意:请注意,您的递归停止逻辑不起作用,如Msp的回答所述。

You need getters for the Pair class (or make alpha and omega attributes public): 您需要使用Pair类的吸气剂(或公开alpha和omega属性):

class Pair {
   int alpha;   // the smaller one 
   int omega; // the bigger one 
   Pair ( int a, int o ) { alpha = a; omega = o; }
   getAlpha () { return alpha; }
   getOmega () { return omega; }
}

And you have to stop the recursion returning a Pair in the base case (lb = ub) 而且您必须停止在基本情况下返回对(lb = ub)的递归

class MinMax{
    public static Pair mmA(int lb, int ub, int[] a){
        int min;
        int max;
        int mid;
        Pair pair1;
        Pair pair2;

        if (ub == lb){
            // Just one item, so min and max are the same
            return Pair(a[lb],a[ub]);
        } else {
            mid = (lb + ub)/2;
            pair1 = mmA (lb, mid, a);                
            pair2 = mmA (mid+1, ub, a);

            min = Math.min(pair1.getOmega(), pair2.getOmega());
            max = Math.max(pair1.getAlpha(), pair2.getAlpha());

            return new Pair(min, max);
        }
    }

    public static void main(String[]args){
        int[] a = {4, 3, 5, 6, 7, 9, 1};
        mmA(0, 6, a);
    }
}

The problem appears that you were never really returning anything and, as @Andreas said, you then aren't combining the results of what you returned. 问题似乎是您从未真正返回过任何东西,正如@Andreas所说,那么您没有合并返回结果。

Here I had to add an extra condition for when the upper index and lower index are adjacent (ie upper - lower = 1) or else an infinite loop would occur. 在这里,我不得不添加一个额外的条件,以便当上索引和下索引相邻时(即上-下= 1),否则将发生无限循环。 Also, I changed your variable names to be more descriptive. 另外,我将您的变量名更改为更具描述性。 I was finding myself getting lost reading it. 我发现自己迷路了。

public class MinMax {

    public static void main(String[] args){
        int[] array = {4, 3, 5, 6, 7, 9, 1};
        Pair result = mmA(0, array.length - 1, array);
        System.out.println("min: " + result.alpha + ", max: " + result.omega);
    }

    public static Pair mmA(int lowerBound, int upperBound, int[] array){
        if (upperBound == lowerBound){
            return new Pair(array[lowerBound], array[upperBound]);
        }
        else if (upperBound - lowerBound == 1) {
            int localAlpha = Math.min(array[lowerBound], array[upperBound]);
            int localOmega= Math.max(array[lowerBound], array[upperBound]);
            return new Pair(localAlpha, localOmega);
        }
        else {
            int midIndex = (lowerBound + upperBound)/2;
            Pair pairA = mmA(lowerBound, midIndex, array);
            Pair pairB = mmA(midIndex, upperBound, array);
            int localAlpha = Math.min(pairA.alpha, pairB.alpha);
            int localOmega= Math.max(pairA.omega, pairB.omega);
            return new Pair(localAlpha, localOmega);
        }
    }

}

class Pair {
    int alpha;   // the smaller one
    int omega; // the bigger one
    Pair ( int alpha, int omega ) {
        this.alpha = alpha;
        this.omega = omega;
    }
}

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

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