代码具体实现如下:
package com.zuoyan.algorithm;
public class FindMinMax {
//Main函数进行测试
public static void main(String[] args) {
int[] a=new int[]{1,10,2,19,365,-2,100,28};
MinMax minMax = getMinMax(a, 0,a.length-1);
System.out.println("最小值:"+minMax.getMin());
System.out.println("最大值:"+minMax.getMax());
}
public static MinMax getMinMax(int [] array,int start,int end){
//分治的终止条件 如果 两个坐标相邻 或者是同一个坐标,返回最小的值和最大的值
if(end-start<=1){
if(array[start]>array[end]){
return new MinMax(array[end],array[start]);
}else
{
return new MinMax(array[start], array[end]);
}
}
else{
//如果开始下标和终止下标没有到达终止下标,求出中间坐标
int mid = (start+end)/2;
MinMax left = getMinMax(array, start, mid);
MinMax right = getMinMax(array, mid+1, end);
int max = 0,min = 0;
min = left.getMin()<right.getMin()?left.getMin():right.getMin();
max = left.getMax()>right.getMax()?left.getMax():right.getMax();
//返回查找的最大最小
return new MinMax(min, max);
}
}
}
class MinMax
{
private int max;
private int min;
public MinMax(int min, int max) {
super();
this.max = max;
this.min = min;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
}