用分治算法同时求数组中的最值
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;
}
}
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;
}
}
相关文章推荐
- CodeForces 552D — Vanya and Triangles 暴力枚举
- 求图的最小生成树
- ubuntu install curl
- leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法
- Java week1
- 查询oracle中所有用户信息
- 树莓派-资源汇总
- android webview 去掉缩放按钮
- 的一维数组成二维阵列
- BZOJ 1023 [SHOI2008]cactus仙人掌图
- linux常用命令
- ssh安全加固
- hdu 1032 The 3n + 1 problem
- 一个典型的双缓冲的例子
- TCP/IP协议的详细介绍
- HDU 2041 超级楼梯
- [2015-07-18] python004
- Android内存控制小技巧-使用矢量图来节省你的内存并简化你的开发。
- Android Studio 如何打JAR包
- android开发之broadcast学习笔记