首页 > 代码库 > 求n的元素的最大最小值

求n的元素的最大最小值

public static int[] maxMin(int a[]) {        int[] res = new int[2];        int len = a.length;        if (len <= 0) {            return res;        }        res[0] = res[1] = a[0];        if (len % 2 == 0) {            for (int i = 0; i < len - 1; i += 2) {                if (a[i] > a[i + 1]) {                    int tem = a[i];                    a[i] = a[i + 1];                    a[i + 1] = tem;                }            }            for (int i = 0; i < len; i += 2) {                if (res[0] > a[i]) {                    res[0] = a[i];                }            }            for (int i = 1; i < len; i += 2) {                if (res[1] < a[i]) {                    res[1] = a[i];                }            }        } else {            for (int i = 0; i < len - 1 - 1; i += 2) {                if (a[i] > a[i + 1]) {                    int tem = a[i];                    a[i] = a[i + 1];                    a[i + 1] = tem;                }            }            for (int i = 0; i < len - 1; i += 2) {                if (res[0] > a[i]) {                    res[0] = a[i];                }            }            for (int i = 1; i < len - 1; i += 2) {                if (res[1] < a[i]) {                    res[1] = a[i];                }            }            if (res[0] > a[len - 1]) {                res[0] = a[len - 1];            } else if (res[1] < a[len - 1]) {                res[1] = a[len - 1];            }        }        return res;    }

两两比较的方法,大的在右边,小的在左边,然后在分别找最大最小值,n是偶数奇数要注意。

求n的元素的最大最小值