This is the fifth day of my participation in the First Challenge 2022
We use the daily sorting scene is relatively more, whether it is brush algorithm or daily business processing; When writing business interfaces, you may prefer to squeeze the interface logic into SQL, where business processing + sorting is done.
The sorting
Array.sort() is the most commonly used sort method. However, the implementation of sorting is based on comparator; The default is sort from smallest to largest; If you need to change the way you sort, such as reverse order, you can override the Comparator interface using an anonymous inner class and implement the compare method.
public static void main(String[] args) {
Integer[] q = new Integer[]{0.4.1, -1.2};
Arrays.sort(q);
System.out.println("From smallest to largest");
for (Integer a :
q) {
System.out.print(a+ "");
}
System.out.println("In reverse order:");
Arrays.sort(q,new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
returno2.compareTo(o1); }});for (Integer a :
q) {
System.out.print(a+""); }}Copy the code
Analysis of the Arrays. Sort
- Arrays. Sort can provide the sorting method parameters only support: int, long, short, char, byte, float, double
- The rest are listed as Object types, such as Integer, the packaging type we use more often
Take the int[] array as an example:
- Click on the method to enter the range of judging a value, QUICKSORT_THRESHOLD = 286
- If we jump into sort, we will enter a read again, INSERTION_SORT_THRESHOLD = 47
- Arrays.sort uses a different sort for different array lengths.
- If the length is less than 286, enter the private method sort and pass the parameter
- If the length is less than 47, use the insertion sort algorithm
- If the length is greater than 47, use the quicksort algorithm
- If the length is greater than 286, judge whether structuration is available (sorting is nearly complete), and judge whether merge sort algorithm is used after grouping.
- If the length is less than 286, enter the private method sort and pass the parameter
The Arrays. Sort of optimization
The arrays. sort method is not a single sort, but a more optimized sorting algorithm based on the internal array length, which is a combination of quicksort, merge sort and insert sort. The details of merge sort and determining whether it is structured will be explained in a later section.
The arrays.sort () method actually uses the strategy mode, which reflects the idea of splitting. The basic steps and algorithms of sorting are unchanged. But what’s changed is the reverse order of the anonymous inner class, the comparator method; Sorting results are determined by the comparator. This is the policy pattern, and the sort generated by different comparators is different policy.