How does Java implement the sorting of collections?
-this article sorts the student object collection as an example
Java via Collections.sort (list<student> stulist) and Collections.sort (list<student> stuList,Comparator c) The two methods implement sorting.
Use the Collections.sort (list) method to implement the ordering:
Step1: Ensure that the student class implements the comparable interface and overrides the CompareTo () method.
Step2: Calls the Collections.sort (List list) method to sort.
1 public class Student implements comparable<student> {2 3 private int, 4 5 public Student (int Age) {6 this.age = age, 7} 8 9 public int getage () {age;11}12 @Override14 public int CompareTo (Student Student) {//Override CompareTo Method (This.age < Student.age)?-1: (Th Is.age = = student.age)? 0:1);}18 public static void Main (string[] args) {list<student> stulist = new ArrayList (); Stulist.add (New Student (5)), Stulist.add (New Student (3)), Stulist.add (New Student (7)); 25 Stulist.add (New Student (2)), Stulist.add (New Student (4)), Stulist.add (New Student (6)); 28 Stulist.add (New Student (1)); Collections.sort (stulist); Call sorting Method for (Student student:stulist) {System.out.println (Student.getage ()); 34}35 }36}
Principle Analysis:
The Step1:collections class calls the List.sort (Comparator C) method, and the comparer C assigns a value of NULL.
1 public static <t extends comparable<? super t>> void Sort (list<t> List) {2 list.sort (null); 3 }
The sort method in the Step2:list interface converts the Stulist collection to an array, sorts it by the Arrays.sort () method, and replaces the sorted element with each element in the stulist.
1 default void sort (comparator<? super E> C) {2 object[] A = This.toarray (); 3 Arrays.sort (A, ( Comparator) c); 4 listiterator<e> i = This.listiterator (); 5 for (Object e:a) {6 i.next (); 7 I.set ((e) e); 8 }9 }
So where exactly is the CompareTo method called?
Enter the Arrays.sort () method:
1 public static <T> void sort (t[] A, comparator<? super T> C) {2 if (c = = null) {3 sort (a); 4
} else {5 if (legacymergesort.userrequested) 6 Legacymergesort (A, c); 7 Else 8 timsort.sort (A, 0, A.length, C, NULL, 0, 0); 9 }10 }
The comparator is not established, so C==null is true to perform the sort (a) method:
1 public static void sort (object[] a) {2 if (legacymergesort.userrequested) 3 legacymergesort (a); 4 ELSE5 Comparabletimsort.sort (A, 0, a.length, NULL, 0, 0); 6 }
legacymergesort.userrequested defaults to False, which indicates whether the traditional merge sort is used, the traditional merge sort is the default sorting method before 1.5, and the Comparabletimsort.sort () method is executed by default after 1.5. The traditional merge sort is mandatory in the program unless it is required. The statements are as follows:
So keep looking at the Comparabletimsort.sort () method:
1 static void sort (object[] A, int lo, int hi, object[] work, int workbase, int worklen) {2 assert A! = NULL && lo >= 0 && lo <= hi && hi <= a.length; 3 4 int nremaining = Hi-lo; 5 if (Nremaining < 2) 6 return; Arrays of size 0 and 1 are all sorted 7 8//If array is small, does a "mini-timsort" with no merges 9 if (Nremaining < min_merge) {ten int initrunlen = countrunandmakeascending (A, lo, hi); binar Ysort (A, lo, hi, lo + initrunlen), return;13}14/**16 * March over the array on CE, finding natural runs,17 * Extending short natural runs to minrun elements, and merging Runs18 * To maintain stack invariant.19 */20 comparabletimsort ts = new Comparabletimsort (A, work, work Base, worklen); int minrun = Minrunlength (nremaining); Identify next Run24 int runlen = countrunandmakeascending (A, lo, HI); tend to min (Minrun, nremaining) if (Runlen < Minrun) {$ int force = nremaining <= min Run? Nremaining:minrun;29 Binarysort (A, lo, lo + force, lo + runlen); Runlen = force;31 }32//Push run onto Pending-run Stack, and maybe Merge34 ts.pushrun (lo, runlen); 35 Ts.mergecollapse (); PNS//Advance to find Next run38 lo + runlen;39 Nrema Ining-= runlen;40} while (nremaining! = 0);/Merge All remaining runs to complete sort43 Assert lo = = hi;44 ts.mergeforcecollapse (); assert ts.stacksize = = 1;46}
The Line4 nremaining indicates the number of objects that are not sorted, and if the number is less than 2 before the method is executed, the order is not required.
If 2<= nremaining <=32, which is the initial value of Min_merge, indicates that the array that needs to be sorted is a decimal group, which can be sorted using the Mini-timsort method, or a merge sort is required.
Mini-timsort Sorting method: First find the array in the first ascending sequence from subscript 0, or to find the descending sequence after the conversion to ascending into the array, the ascending array as the initial array, after each element is sorted by a dichotomy into the initial array. Note that the CompareTo () method We have rewritten is called here.
method to get the initial array:
1 private static int countrunandmakeascending (object[] A, int lo, int hi) {2 assert lo < hi; 3 int runhi = Lo + 1; 4 if (runhi = = hi) 5 return 1; 6 7 //Find end of run, and reverse range if descending 8 if ((Compara ble) a[runhi++]). CompareTo (A[lo]) < 0) {//Descending 9 while (Runhi < Hi && ((comparable) A[RUNHI]). Co Mpareto (A[runhi-1]) < 0) runhi++;11 reverserange (A, lo, runhi), n } else { //ASCENDING13 While (Runhi < Hi && ((comparable) A[RUNHI]). CompareTo (a[runhi-1]) >= 0) runhi++;15 } (+) return runhi-lo;18 }
According to the program example, A[1].compareto (A[0]) <0, so the downward cycle to see A[2].compareto (a[1]) <0, A[3].compareto (a[2]) <0 and so on, we found a[2]. CompareTo (a[1]) <0 is not true, so the loop terminates, gets to the longest descending array of a[]{5,3}, and then calls the Reverserange () method to arrange it in ascending order of a[]{3,5}, as the initial array, initrunlen=2. The binary insertion operation is followed by the following code:
1 private static void Binarysort (object[] A, int lo, int hi, int start) {2 assert lo <= start && star T <= Hi; 3 if (start = = lo) 4 start++; 5 for (; start < hi; start++) {6 Comparable pivot = (comparable) A[start]; 7 8//Se T left (and right) to the index where A[start] (pivot) belongs 9 int left = lo;10 int right = Star T;11 assert left <= right;12/*13 * invariants:14 * Pivot >= All In [Lo, left]. * Pivot < All in [right, start]. */17 while (left < rig HT) {$ int mid = (left + right) >>> 1;19 if (Pivot.compareto (a[mid)) < 0) 20 right = Mid;21 Else22 left = mid + 1;23}24 Assert left = = right;25/*27 * The invariants still holD:pivot >= all on [Lo, left] AND28 * Pivot < all on [left, start], so pivot belongs on left. Note29 * that if there is elements equal to pivot, left points to The30 * First slots after them -That's why this-sort is stable.31 * Slide elements-to-make-for-pivot.32 */33 int n = start-left; The number of elements to move34//Switch is just a optimization for arraycopy in default case35 Switch (n) {2:a[left case + 2] = a[left + 1];37 case 1:a[left + 1] = a[left];38 Break;39 Default:System.arraycopy (A, left, a, left + 1, n); 40}41 A[left] = pivot;42}43}
Loops through all the elements of the subscript >=2, inserting it into an appropriate place in the initial array by means of a dichotomy, so that the ability to sort by calling the element's CompareTo () method is complete.
Use the Collections.sort (List list,comparator C) method to implement the ordering:
This method passes in a comparer to compare the size of each element. The method does not require elements to implement the comparable interface, but requires an implementation class that implements the comparator interface to instantiate a comparer, noting that the comparator here is an interface rather than a class. The method of anonymous inner classes is usually used here.
1 Collections.sort (Stulist, New comparator<student> () {2 @Override3 public int compare (Student stu1, Student stu2) {4 return (Stu1.getage () < Stu2.getage ())?-1: (stu1.getage () = = Stu2.getage ()? 0:1); 5 }6
});
This method implements sorting in the same way as the above method.
First call the Collections.sort () method, pass in the collection and comparer, and the sort () method calls the list's sort method, passing in the comparer. (Ibid. Step1) code is as follows:
1 public static <T> void sort (list<t> List, comparator<? super T> C) {2 list.sort (c); 3 }
The sort () method in the list calls the Arrays.sort () method, passing in the array and the comparer. (Ibid. Step2)
1 default void sort (comparator<? super E> C) {2 object[] A = This.toarray (); 3 Arrays.sort (A, (Comparator) c) ; 4 listiterator<e> i = This.listiterator (); 5 for (Object e:a) {6 i.next (); 7 I.set ((e) e); 8 }9}
The Arrays.sort method calls the Timsort.sort () method with the following code:
1 public static <T> void sort (t[] A, comparator<? super T> C) {2 if (c = = null) {3 sort (a); 4
} else {5 if (legacymergesort.userrequested) 6 Legacymergesort (A, c); 7 Else 8 timsort.sort (A, 0, A.length, C, NULL, 0, 0); 9 }10 }
There is only one point in the Legacymergesort (a,c) and Timsort.sort () methods that differ from methods in that method one uses A.compareto (b) For comparison and method two uses Comparator.compare (A, B) are compared, others are the same.
1 private static <T> int countrunandmakeascending (t[] A, int lo, int hi, 2 comparator<? Super T> C) {3
assert Lo < hi; 4 int runhi = lo + 1; 5 if (runhi = = hi) 6 return 1; 7 8 //Find end of run, and reverse range if desc Ending 9 if (C.compare (a[runhi++], A[lo]) < 0) {//Descending10 while (Runhi < hi && C.compare (a[ru NHi], A[runhi-1]) < 0) One runhi++;12 reverserange (A, lo, runhi), or else { //Ascending14 while (Runhi < hi && c.compare (A[runhi], a[runhi-1]) >= 0) runhi++;16 }17 return Runhi -Lo;19 }
Summarize:
1.collections.sort () Sorting has two implementations, one is to allow the element class to implement the comparable interface and overwrite the CompareTo () method, and the second is to pass the Collecitons.sort () method to the comparator, usually in the form of anonymous inside.
2.collections.sort () is sorted by calling the Arrays.sort () method, and in java1.6+, if the collection size <32 the tim-sort algorithm, if >=32 is sorted by merge.
Java Collection sorting function implementation analysis