您的位置:首页 > 其它

用分治算法同时求数组中的最值

2015-07-19 16:35 393 查看
//根据别人的最大值代码改写分治法求数组的最大值最小值

public class MaxAndMin {

     public static void main(String[] args){      

        int AR[] = { 0,3, 4, 62, 70, 23, 120, 34, 800,-1};

        int[] res=maxandminNum(AR,0,(AR.length-1));

        System.out.println("MAX: "+res[0]+",MIN: "+res[1]);

     }

     public static int[] maxandminNum(int arrary[],int left,int right)

     {

      int maxLeft,maxRight;

      int[] leftres=new int[2];//左边的最值

      int[] rightres=new int[2];//右边子模块的最值

      if(left == right)

      {

       leftres[0]=leftres[1]=rightres[0]=rightres[1]=left;//下标为0代表最大值,下标为1代表最小值

       return leftres;

      }

      leftres = maxandminNum(arrary,left,(left+right)/2);

      rightres = maxandminNum(arrary,(left+right)/2 + 1,right);

      System.out.println(leftres[0]+","+ leftres[1]+","+rightres[0]+","+rightres[1]);

      if(arrary[leftres[0]] > arrary[rightres[0]]&&arrary[leftres[1]] < arrary[rightres[1]]) ;

      if(arrary[leftres[0]] > arrary[rightres[0]]&&arrary[leftres[1]] > arrary[rightres[1]]) leftres[1]=rightres[1];

      if(arrary[leftres[0]] < arrary[rightres[0]]&&arrary[leftres[1]] > arrary[rightres[1]]) leftres=rightres;    

      if(arrary[leftres[0]] < arrary[rightres[0]]&&arrary[leftres[1]] < arrary[rightres[1]]) leftres[0]=rightres[0];

      System.out.println(leftres[0]+","+ leftres[1]+","+rightres[0]+","+rightres[1]);

      return leftres;

     }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: