分治法(1)

来源:互联网 发布:黑色沙漠兽娘捏脸数据 编辑:程序博客网 时间:2024/05/29 11:11

1 利用分治法求某一数组的最大值和最小值

public class MinMax {public void minmax(int[] a,int[] rec,int low,int high){int mid;int[] rec2=new int[2];//rec2[0]记录最小值,rec2[1]记录最大值if(high==low){rec[0]=rec[1]=a[high];}else if(high-low==1){if(a[low]<a[high]){rec[0]=a[low];rec[1]=a[high];}else{rec[0]=a[high];rec[1]=a[low];}}else {mid=(high-low)/2+low;minmax(a,rec,low,mid);minmax(a,rec2,mid+1,high);if(rec2[0]<rec[0])rec[0]=rec2[0];if(rec2[1]>rec[1])rec[1]=rec2[1];}}public static void main(String []args){int record[]={0,0};//record[0]记录最小值,record[1]记录最大值int array[]={19,3,5,70,9,11,13,15,17,16};new MinMax().minmax(array,record,0,9);System.out.println("Max="+record[1]+",Min="+record[0]);}}

0 0