Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The illustration | 5 ways For Java to find the maximum value in an array!


May 31, 2021 Article blog


Table of contents


This article comes from the public number: Java Chinese Community Author: Lei ge

We've had problems finding maximum values in specific scenarios, such as checking for the highest salary for a company employee, the highest grade in a class, or an interview, so let's list the five ways to query the maximum value in an array.

 The illustration | 5 ways For Java to find the maximum value in an array!1

First, let's look at the most primitive and "stupid" approach to implementation: circular and recursive comparisons.

Mode 1: Loop comparison

The execution flow of the loop comparison is shown in the following diagram:

 The illustration | 5 ways For Java to find the maximum value in an array!2

As can be seen from the figure above, the core of the loop comparison is to define a maximum value, and then loop against each element, if the value of the element is greater than the maximum value to update the maximum value of this element, and then make the next comparison, until the end of the loop we can find the maximum value, the implementation code is as follows:

public class ArrayMaxTest {
    public static void main(String[] args) {
        int[] arr = {3, 7, 2, 1, -4};
        int max = findMaxByFor(arr); // 查找最大值
        System.out.println("最大值是:" + max);
    }


    /**
     * 通过 for 循环查找最大值
     * @param arr 待查询数组
     * @return 最大值
     */
    private static int findMaxByFor(int[] arr) {
        int max = 0; // 最大值
        for (int item : arr) {
            if (item > max) { // 当前值大于最大值,赋值为最大值
                max = item;
            }
        }
        return max;
    }
}

The results of the above procedures are:

The maximum value is: 7

Mode 2: Recursive comparison

The core of the recursive comparison is to define two positions (start and end positions), to compare the size of the start and end position values each time, to set the maximum value to the value of the start position when the value of the start position is greater than the value of the end position, and then to set the end position -1 (move one bit forward) to continue the recursive call; The maximum value can be returned until the end of recursion, and the execution process is shown in the following diagram:

 The illustration | 5 ways For Java to find the maximum value in an array!3

The implementation code is as follows:

public class ArrayMax {
    public static void main(String[] args) {
        int[] arr = {3, 7, 2, 1, -4};
        int max = findMaxByRecursive(arr, 0, arr.length - 1, 0); // 根据 Collections 查找最大值
        System.out.println("最大值是:" + max);
    }


    /**
     * 根据递归查询最大的值
     * @param arr  待查询数组
     * @param head 最前面的元素的下标
     * @param last 最末尾的元素的下标
     * @param max  (临时)最大值
     * @return 最大值
     */
    private static int findMaxByRecursive(int[] arr, int head, int last, int max) {
        if (head == last) {
            // 递归完了,返回结果
            return max;
        } else {
            if (arr[head] > arr[last]) {
                max = arr[head]; // 赋最大值
                // 从后往前移动递归
                return findMaxByRecursive(arr, head, last - 1, max);
            } else {
                max = arr[last]; // 赋最大值
                // 从前往后移动递归
                return findMaxByRecursive(arr, head + 1, last, max);
            }
        }
    }
}

The results of the above procedures are:

The maximum value is: 7

Mode 3: Rely on Arrays.sort() implementation

The array can be sorted from small to large according to Arrays.sort method, and when the sort is complete, the last value is the maximum value, and the implementation code is as follows:

import java.util.Arrays;


public class ArrayMax {
    public static void main(String[] args) {
        int[] arr = {3, 7, 2, 1, -4};
        int max = findMaxBySort(arr); // 根据 Arrays.sort 查找最大值
        System.out.println("最大值是:" + max);
    }


    /**
     * 根据 Arrays.sort 查找最大值
     * @param arr 待查询数组
     * @return 最大值
     */
    private static int findMaxBySort(int[] arr) {
        Arrays.sort(arr);
        return arr[arr.length - 1];
    }
}

The results of the above procedures are:

The maximum value is: 7

Mode 4: Implemented according to Arrays.stream().

stream is one of the new core features of JDK 8, and with it we can easily implement many functions, such as finding the maximum, minimum, and so on, the implementation code is as follows:

import java.util.Arrays;


public class ArrayMax {
    public static void main(String[] args) {
        int[] arr = {3, 7, 2, 1, -4};
        int max = findMaxByStream(arr); // 根据 stream 查找最大值
        System.out.println("最大值是:" + max);
    }


    /**
     * 根据 stream 查找最大值
     * @param arr 待查询数组
     * @return 最大值
     */
    private static int findMaxByStream(int[] arr) {
        return Arrays.stream(arr).max().getAsInt();
    }
}

The results of the above procedures are:

The maximum value is: 7

Mode 5: Rely on collections .max() implementations

You can also find the maximum and minimum values using the Collections collection tool class, but before we use them we want to convert arrays into collections (Lists) with the following implementation code:

import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
import java.util.Collections;


public class ArrayMax {
    public static void main(String[] args) {
        int[] arr = {3, 7, 2, 1, -4};
        int max = findMaxByCollections(arr); // 根据 Collections 查找最大值
        System.out.println("最大值是:" + max);
    }


    /**
     * 根据 Collections 查找最大值
     * @param arr 待查询数组
     * @return 最大值
     */
    private static int findMaxByCollections(int[] arr) {
        List<Integer> list = Arrays.asList(
                org.apache.commons.lang3.ArrayUtils.toObject(arr));
        return Collections.max(list);
    }
}

The results of the above procedures are:

The maximum value is: 7

Extended knowledge: How the Arrays.sort method works

To understand how Arrays#sort method works, we looked at the core of the source sort method, which is sorted through loops, as follows:

for (int i = left, j = i; i < right; j = ++i) {
 int ai = a[i + 1];
 while (ai < a[j]) {
  a[j + 1] = a[j];
  if (j-- == left) {
   break;
  }
 }
 a[j + 1] = ai;
}

The execution process is shown in the following diagram:

 The illustration | 5 ways For Java to find the maximum value in an array!4

summary

This article describes the methods for querying the maximum values in an array, which can be divided into large dimensions: manual implementation and interface-dependent implementation. Manual implementations are primarily through looping and recursive comparisons, but this approach is not recommended stream because it is not elegant enough;

Here's the W3Cschool编程狮 | about illustrations 5 ways For Java to find the maximum value in an array! Related to the introduction, I hope to help you.