Java代码同时求数列的最大值与最小值
转自:http://blog.csdn.net/zhangheliang2010/article/details/8107785
package agrisom; /** * 同时求最大值与最小值 */ public class FindMaxAndMin { public void findMaxAndMin(int [] array){ int length=array.length; int max,min; if(length==0){ System.out.println("array empty"); System.exit(1); }else if(length==1){ max=min=array[0]; }else if(length==2){ max=array[0]>array[1] ? array[0] : array[1]; min=array[0]>array[1] ? array[1] : array[0]; } int i; if((length & 1)==1){ //数组长度为奇数 max=min=array[0]; i=1; }else{ //数组长度为偶数 max=array[0]>array[1] ? array[0] : array[1]; min=array[0]>array[1] ? array[1] : array[0]; i=2; } for(;i<length;i+=2){ if(array[i] > array[i+1]){ max=max<array[i] ? array[i] : max; min=min>array[i+1] ? array[i+1] : min; }else{ max=max<array[i+1] ? array[i+1] : max; min=min>array[i] ? array[i] : min; } } System.out.println("max: "+max); System.out.println("min: "+min); } public static void main(String [] args){ FindMaxAndMin fmm=new FindMaxAndMin(); fmm.findMaxAndMin(new int []{4,3,6,9,1,56,22}); fmm.findMaxAndMin(new int []{4,3,6,9,1,56}); fmm.findMaxAndMin(new int []{4,3}); fmm.findMaxAndMin(new int []{2}); fmm.findMaxAndMin(new int []{}); } } /** 运行结果: max: 56 min: 1 max: 56 min: 1 max: 4 min: 3 max: 2 min: 2 array empty */