Home  >  Article  >  Java  >  How to sort using Java's Arrays class

How to sort using Java's Arrays class

PHPz
PHPzforward
2023-04-27 11:01:061082browse

1.Arrays.sort(int[] a)

This form is to sort all the elements of an array in order from small to large.

2.Arrays.sort(int[] a, int fromIndex, int toIndex)

This form is to partially sort the array, that is, to sort the array a Sort elements with subscripts from fromIndex to toIndex-1. Note: elements with subscripts to toIndex do not participate in sorting.

3. public static void sort(T[] a,int fromIndex, int toIndex, Comparator c)

Users can Custom sorting.

4. Sort instance

package leetcode;
 
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
 
/**
 * @author zhangyu
 * @Description: Arrays.sort()可以使用内部的比较器进行比较,也可以自己定义比较器进行逆序排序
 * @date 2018/12/10 14:06
 **/
public class ArraysSortTest2 {
    @Test
    public void testArraysSort() {
        Integer[] nums = {5, 2, 1, 3, 4, 9, 0, 7, 8, 6};
        Arrays.sort(nums, new Comparator<Integer>() {
            @Override
            public int compare(Integer a, Integer b) {
                if (a > b) {
                    return -1;
                } else if (a == b) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });
    }
}

The above is the detailed content of How to sort using Java's Arrays class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete