[算法设计]分治思想实例——最大值最小值(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 @   Masahiko  阅读(398)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
点击右上角即可分享
微信分享提示