Several ways of custom sorting in Java

1, Common type array int []

For ordinary data type Arrays, several methods are provided in the Arrays class of Java:

  • Arrays.sort(int[] a): arranges the specified array in numerical order
  • sort(int[] a, int fromIndex, int toIndex): sort the specified range of the array in ascending order
  • Arrays.parallelSort(int[] a): arranges the specified array in numerical order
  • Arrays.parallelSort(int[] a, int fromIndex, int toIndex): arranges the specified range of the array in numerical order

For other basic type arrays, there is the same method. You can directly replace the parameters with other basic type arrays. Note that these methods can only sort in ascending order and cannot customize sorting rules.

2, Wrapper type array Integer []

For reference type Arrays, the Arrays class of Java provides the following sorting methods:

  • Arrays.parallelSort(T[] a): an array of specified objects arranged in ascending order according to the elements of natural ordering.
  • Arrays. Parallelsort (t [] A, comparator <? Super T > CMP): sorts the specified object array according to the order raised by the specified comparator.
  • Arrays.parallelSort(T[] a, int fromIndex, int toIndex): the elements of the array arranged in ascending order according to the natural ordering within the specified range of the specified object.
  • Arrays. Parallelsort (t [] A, int fromindex, int toindex, comparator <? Super T > CMP): sorts the specified range of the specified object array according to the order raised by the specified comparator.
  • Arrays. Sort (t [] A, comparator <? Super T > C): sort the specified object array according to the order raised by the specified comparator.
  • Arrays. Sort (t [] A, int fromindex, int toindex, comparator <? Super T > C): sort the specified range of the specified object array according to the order raised by the specified comparator.

Note that the method parameter contains Comparator <? The methods of super T > C can be customized by implementing the compare(T o1, T o2) method in the Comparator interface. Examples are as follows:

public class Solution {
    public String sort(Integer[] nums) {
        Arrays.sort(nums, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
            	//Sort from large to small
                return o2 - o1;
            }
        });
        return Arrays.toString(nums);
    }
}

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        Integer[] arr = {1, 2, 3, 4, 5};
        System.out.println(solution.sort(arr));
    }
}

Output result: [5, 4, 3, 2, 1]

When customizing sorting, the most important is the compare(Integer o1, Integer o2) method. The return value of this method determines the final sorting result. In this method, the parameter o1 represents the element on the right side of the array, and o2 represents the element on the left side of the array. Of course, o1 and o2 are always adjacent elements in the array. So how to determine the return value? Just remember the following conclusions:

  • Return value < 0: exchange the position of o1 and o2
  • Return value = 0: no position exchange, no sorting
  • Return value > 0: the positions of o1 and o2 are not exchanged

Then, when we need to sort an out of order array in ascending order, we just need to write it as follows:

public class Solution {
    public String sort(Integer[] nums) {
        Arrays.sort(nums, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                //It is written to verify the values of O1 and O2. It is not necessary to write these two lines at ordinary times
                System.out.println("o1= " + o1);
                System.out.println("o2= " + o2);
                return o1 - o2;
            }
        });
        return Arrays.toString(nums);
    }
}

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        Integer[] arr = {5, 1, 3, 2, 4};
        System.out.println(solution.sort(arr));
    }
}

Output results:
o1= 1
o2= 5
o1= 3
o2= 1
o1= 3
o2= 5
o1= 3
o2= 1
o1= 2
o2= 3
o1= 2
o2= 1
o1= 4
o2= 3
o1= 4
o2= 5
[1, 2, 3, 4, 5]

You can see that when O1 > O2 (that is, when the value of the right element is greater than the value of the left element), o1-o2 > 0. At this time, we do not need to exchange O1 and O2, so O1 and O2 are in ascending order. If you want to sort in descending order, just change the return o1 - o2; statement to return o2 - o1.

3, Sorting of object arrays

There are two ways to customize the sorting of object arrays:

  • Class implements the Comparable interface, implements the compareTo(T o) method, and then calls Arrays.sort(Object o) method or sort(Object[] a, int fromIndex, int toIndex) method
  • Using the same method as the wrapper type array, implement the compare(T o1, T o2) method in the Comparator interface to realize user-defined sorting

3.1 method 1: implement Comparable interface

First define an Employee class to implement the Comparable interface:

public class Employee implements Comparable<Employee>{
    public String name;
    public Integer salary;

    public Employee(String name, Integer salary){
        this.name = name;
        this.salary = salary;
    }

	//Key methods of sorting
    @Override
    public int compareTo(Employee e) {
        if (this.salary > e.salary){
            return 1;
        }else if (this.salary < e.salary){
            return -1;
        }else{
            return 0;
        }
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                '}';
    }
}

public class Solution {
    public Employee[] sort1(Employee[] nums) {
        Arrays.sort(nums);
        return nums;
    }
}

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        Employee zhangsan = new Employee("Zhang San", 1000);
        Employee lisi = new Employee("Li Si", 2000);
        Employee wangwu = new Employee("Wang Wu", 3000);
        Employee[] arr1 = {lisi, wangwu, zhangsan};
        Employee[] sort1 = solution.sort1(arr1);
        System.out.println("------------Method 1---------------");
        for (Employee e : sort1){
            System.out.println(e);
        }
}

Output results:
------------Method 1---------------
Employee{name = 'Zhang San', salary=1000}
Employee{name = 'Li Si', salary=2000}
Employee{name = 'Wang Wu', salary=3000}

The key method to realize sorting is compareTo(Employee e) method, and its return value also determines the sorting result. Here is this Salary is actually equivalent to o1 in the compare(Integer o1, Integer o2) method. It points to the next element in the array, and e.salary points to the previous element in the array, which is equivalent to o2. Note that the former element and the latter element mentioned here are relative to two adjacent elements, because in essence, these two methods compare between adjacent elements. At this point, you should know that its return value is the same as that of the compare(Integer o1, Integer o2) method mentioned earlier.

3.2 method 2: implement the compare(T o1, T o2) method in the Comparator interface

public class Employee2 {
    public String name;
    public Integer salary;

    public Employee2(String name, Integer salary){
        this.name = name;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                '}';
    }
}

public class Solution {
    public Employee[] sort2(Employee[] nums){
        Arrays.sort(nums, new Comparator<Employee>() {
            @Override
            public int compare(Employee o1, Employee o2) {
                return o1.salary - o2.salary;
            }
        });
        return nums;
    }
}

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        Employee zhangsan = new Employee("Zhang San", 1000);
        Employee lisi = new Employee("Li Si", 2000);
        Employee wangwu = new Employee("Wang Wu", 3000);
        System.out.println("------------Method 2---------------");
        Employee[] arr2 = {lisi, wangwu, zhangsan};
        Employee[] sort2 = solution.sort2(arr2);
        for (Employee e : sort2) {
            System.out.println(e);
        }
    }
}

Output results:
------------Method 2---------------
Employee{name = 'Zhang San', salary=1000}
Employee{name = 'Li Si', salary=2000}
Employee{name = 'Wang Wu', salary=3000}

You can see that method 2 is actually the same as the wrapper type array, because the elements in the wrapper type array are not essentially different from those in the object array. They are all references to objects.

4, Sorting of sets (containers)

Keywords: Java JavaSE

Added by gavinbsocom on Mon, 20 Dec 2021 20:44:13 +0200