找出数组中元素的最大值和最小值

package com.coolinkiot.utils;

/**
 * @data Administrator
 * @data 2020/9/2 0002
 */
public class MaxMIn {

    private int max;
    private int min;

    public int getMax() {
        return max;
    }

    public int getMin() {
        return min;
    }

    public void getMaxAndMin(int[] arr) {
        if (arr == null) {
            return;
        }
        int len = arr.length;
        max = arr[0];
        min = arr[0];
        for (int i = 0; i < len - 1; i += 2) {
            if (arr[i] > arr[i + 1]) {
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        min = arr[0];
        for (int i = 2; i < len; i += 2) {
            if (arr[i] < min) {
                min = arr[i];
            }
        }
        max = arr[1];
        for (int i = 3; i < len; i += 2) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        if (len % 2 == 1) {
            if (max < arr[len - 1]) {
                max = arr[len - 1];
            }
            if (min > arr[len - 1]) {
                min = arr[len - 1];
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {7, 3, 19, 40, 4, 7, 1};
        MaxMIn m = new MaxMIn();
        m.getMaxAndMin(arr);
        System.out.println("max=" + m.getMax());
        System.out.println("min=" + m.getMin());
    }
}

你可能感兴趣的:(找出数组中元素的最大值和最小值)