Loading

[算法设计]分治思想实例——最大值最小值(Java实现)

public class MaximunandMinimum {
    
    public static void main(String[] arges) {
        //测试函数
        int[] a = new int[] {6,10,32,8,19,20,2,14};
        
        Returnumb ans = getMaxMin(a,0,a.length-1);
        
        System.out.println(ans.getMax());
        System.out.println(ans.getMin());
    }

    public static Returnumb getMaxMin(int[] a,int begin,int end) {
        
        if(end - begin <= 1) {            //元素小于2个,直接找出最大最小值
            if(a[begin]>a[end])
                return new Returnumb(a[end],a[begin]);
            else
                return new Returnumb(a[begin],a[end]);
        }
        else {                           //否则进入递归
            int center = (begin+end)/2;
            
            Returnumb left = getMaxMin(a,begin,center);  //向下分为左右两部分
            Returnumb right = getMaxMin(a,center,end);
            
            int max = Integer.MIN_VALUE;   //初始化最大值和最小值
            int min = Integer.MAX_VALUE;
            
            min = left.getMin()>right.getMin()? right.getMin():left.getMin();   //两个较小值取最小
            max = left.getMax()<right.getMax()? right.getMax():left.getMax();   //两个较大值取最大
            
            return new Returnumb(min,max);  //向上归并
        } 
    }
}

public class Returnumb {
    private int Max;
    private int Min;
    //封装一个类,用作返回最大值和最小值
    public Returnumb(int min,int max) {
        setMax(max);
        setMin(min);
    }
    //成员方法
    public int getMax() {
        return Max;
    }
    public void setMax(int max) {
        Max = max;
    }
    public int getMin() {
        return Min;
    }
    public void setMin(int min) {
        Min = min;
    }
}

(总结自网易云课堂《算法设计与分析之入门篇》)

posted @ 2020-11-22 15:13  Masahiko  阅读(403)  评论(0)    收藏  举报