How to find the maximum and minimum values in an array (by two-element method)

Take the two-element method. Maintain two variables MAX_VALUE and MIN_VALUE, MAX_VALUE is marked as the maximum value, MIN_VALUE is marked as the minimum value, compare two adjacent numbers each time , the larger one is compared with max, and the smaller one is compared with min , and the maximum and value are found by comparison The minimum value, the number of comparisons for this method is 1.5N times

The sample code is as follows:

public class LookForTheMaximumAndMinimumValuesInTheArray {
    static int MAX_VALUE;
    static int MIN_VALUE;
    public static void GetMaxAndMinByArray(int arr[]) {
        MAX_VALUE = arr[0];
        MIN_VALUE = arr[0];
        int arrLength = arr.length;
        for (int i = 1; i < arrLength - 1; i += 2) {
            if (i + 1 > arrLength) {
                if (arr[i] > MAX_VALUE) MAX_VALUE = arr[i];
                if (arr[i] < MIN_VALUE) MIN_VALUE = arr[i];
            }
            //大的跟大的比 小的跟小的比~
            if (arr[i] > arr[i+1]) {
                if (arr[i] > MAX_VALUE) MAX_VALUE = arr[i];
                if (arr[i+1] < MIN_VALUE) MIN_VALUE = arr[i+1];
            }
            if (arr[i] < arr[i+1]) {
                if (arr[i+1] > MAX_VALUE) MAX_VALUE = arr[i+1];
                if (arr[i] < MIN_VALUE) MIN_VALUE = arr[i];
            }
        }

    }

    public static void main(String[] args) {
        int[] array = {520, 20, 100, 1, 3, 20, 52,1314,5200,1314};
        GetMaxAndMinByArray(array);
        System.out.println("当前数组中最大值为:" + MAX_VALUE);
        System.out.println("当前数组中最小值为:" + MIN_VALUE);
    }
}

The result of the operation is as follows:

 Personal summary:

It’s good to read it through debug~ I feel that most of them still use the problem decomposition method . Divide this kind of problem into two steps, first find the maximum value, and then find the minimum value, that is, it will traverse the array twice, and the efficiency is not as good as this two-element method.

Guess you like

Origin blog.csdn.net/lps12345666/article/details/130167264