查找数组中的最大值和最小值

三种方式查找数组中最大值和最小值

第三种个人觉得很好。

public class ArrayAlg {

    public static void main(String[] args) {
        //找数组中的最大值
        double[] doubles={22.1,32.5,56.2,45.2,78.2};
        /* 方法一:Arrays.sort(doubles);
        System.out.println(Arrays.toString(doubles));
        System.out.println("最大值为:"+doubles[doubles.length-1]);
        System.out.println("最小值为:"+doubles[0]);
         */

        /*方法二:double max=doubles[0];
        for (int i=0;i<doubles.length-1;i++){
           if (max<doubles[i+1]){
               max=doubles[i+1];
           }
        }
        System.out.println("最大值为:"+max);

        double min=doubles[0];
        for (int i=0;i<doubles.length-1;i++){
            if (min>doubles[i+1]){
                min=doubles[i+1];
            }
        }
        System.out.println("最小值为:"+min);
        */

        /*方法三:double min=Double.POSITIVE_INFINITY;
        double max=Double.NEGATIVE_INFINITY;
        for (double d:doubles){
            if (min>d){
                min=d;
            }
            if (max<d){
                max=d;
            }
        }
        System.out.println("最大值为:"+max+"最小值"+min);
         */
    }


}

猜你喜欢

转载自www.cnblogs.com/liu-chen/p/11924690.html