A Simple Analysis of the source code of the sort () method in Collections, collectionssort

Source: Internet
Author: User
Tags comparable

A Simple Analysis of the source code of the sort () method in Collections, collectionssort

  • The sort method code of Collections:
    public static <T> void sort(List<T> list, Comparator<? super T> c) {        Object[] a = list.toArray();        Arrays.sort(a, (Comparator)c);        ListIterator i = list.listIterator();        for (int j=0; j<a.length; j++) {            i.next();            i.set(a[j]);        }    }
Definition of this method: <T extends Comparable <? Super T> indicates that the generic parameters passed in this method must implement the compareTo (T o) method in Comparable; otherwise, the sort sorting cannot be performed.

This method is divided into three steps:

(1) Replace list with an object Array

(2) pass this object array to the sort method of the Arrays class (that is to say, the sort of collections actually calls Arrays. sort)

(3) After sorting, copy the Arrays elements to the List one by one.

  • The Collections method actually calls the Arrays sort method to implement it. Let's look at the Arrays sort method code:
    public static void sort(Object[] a, int fromIndex, int toIndex) {        if (LegacyMergeSort.userRequested)            legacyMergeSort(a, fromIndex, toIndex);        else            ComparableTimSort.sort(a, fromIndex, toIndex);    }
Note that sort in section 1.7 has a branch judgment. When LegacyMergeSort. userRequested is true, legacyMergeSort is used; otherwise, ComparableTimSort is used. The literal meaning of LegacyMergeSort. userRequested is probably the meaning of "Traditional Merge Sorting of user requests". This branch calls the same method as jdk1.5 to implement the function.

ComparableTimSort is the improved Merge Sorting, which is especially optimized for the O (n ^ 2) feature when the sorted input has been reversed. Reduce backtracing for input with forward sorting. It is better to process the input in two cases (ascending or descending) (from Baidu encyclopedia ).

  • LegacyMergeSort code:
    private static void legacyMergeSort(Object[] a,                                        int fromIndex, int toIndex) {        rangeCheck(a.length, fromIndex, toIndex);        Object[] aux = copyOfRange(a, fromIndex, toIndex);        mergeSort(aux, a, fromIndex, toIndex, -fromIndex);    }
  • MergeSort code:
 private static void mergeSort(Object[] src,                                  Object[] dest,                                  int low,                                  int high,                                  int off) {        int length = high - low;        // Insertion sort on smallest arrays        if (length < INSERTIONSORT_THRESHOLD) {            for (int i=low; i

①: This method receives two Arrays: Object [] src and Object [] dest. According to the method called, we can see that after sorting the elements in the array of dest, the passed List <T> list is sorted, and the src [] array is used for mediation, that is, the subsequent methods need to be called (so the two arrays must be differentiated ), here, we have a judgment condition: length <INSERTIONSORT_THRESHOLD, and INSERTIONSORT_THRESHOLD is a constant of 7 in Arrays. It defines that if the array element is smaller than 7, it will be directly sorted using the swap method, the program execution efficiency is improved.

②: When the array element is greater than 7, the program first splits the array into two intervals: Low interval and high interval, and then calls two recursion to sort these two interval elements. In recursion, You have to determine whether there are more than seven divided interval elements. If there are more than seven elements, you can continue to divide them into two intervals so that recursive calls can be made cyclically. In this method, pay special attention to the parameter transfer location of src [] and dest []. when calling the recursive method, the src [] array is used as the sorting object for sorting, after src [] is sorted, sort the dest [] array by src through ③ or ④. The final result is the List <T> list sorting result.

③: If the number of initial elements is greater than or equal to 7 (if the number of initial elements is smaller than 7, return the result in sequence in method 1), there are only two situations after Method 2: there are two low-and high-order intervals. The function of this method is: if the highest element in the low interval list is smaller than the lowest element in the high interval list, it indicates that the interval segment of the recursive loop has been sorted, then copy the data to the dest [] array. Otherwise, enter Method 4.

④: This method indicates that the highest number element in the Lower Interval of the recursive loop is greater than the lowest element in the high interval list, that is to say, the element values of the Low-interval array are greater than the element values of the High-interval array. Therefore, the elements of the High-interval and Low-interval in src are swapped into the dest array. In this way, a recursive loop is called. If there are loops, the sorting continues. Otherwise, the sorting is completed.

  • ComparableTimSort. sort (a) code:
static void sort(Object[] a, int lo, int hi) {        rangeCheck(a.length, lo, hi);        int nRemaining  = hi - lo;        if (nRemaining < 2)            return;  // Arrays of size 0 and 1 are always sorted        // If array is small, do a "mini-TimSort" with no merges        if (nRemaining < MIN_MERGE) {            int initRunLen = countRunAndMakeAscending(a, lo, hi);            binarySort(a, lo, hi, lo + initRunLen);            return;        }        /**         * March over the array once, left to right, finding natural runs,         * extending short natural runs to minRun elements, and merging runs         * to maintain stack invariant.         */        ComparableTimSort ts = new ComparableTimSort(a);        int minRun = minRunLength(nRemaining);        do {            // Identify next run            int runLen = countRunAndMakeAscending(a, lo, hi);            // If run is short, extend to min(minRun, nRemaining)            if (runLen < minRun) {                int force = nRemaining <= minRun ? nRemaining : minRun;                binarySort(a, lo, lo + force, lo + runLen);                runLen = force;            }            // Push run onto pending-run stack, and maybe merge            ts.pushRun(lo, runLen);            ts.mergeCollapse();            // Advance to find next run            lo += runLen;            nRemaining -= runLen;        } while (nRemaining != 0);        // Merge all remaining runs to complete sort        assert lo == hi;        ts.mergeForceCollapse();        assert ts.stackSize == 1;    }
 

Refer:

Http://zoujialiang.iteye.com/blog/866902

Http://blog.csdn.net/pickless/article/details/9297895

Http://jxlanxin.iteye.com/blog/1814164


Java Collectionssort usage

CompareTo returns a value (-, 1.
The compare method of the PriceComparator class calls compareTo, And the return value is also one of (-, 1.

The Collections. sort method is to compare and sort the elements of the list according to the compare method of the PriceComparator class.
I have not read the source code of Collections. sort. I Don't Know What sort method he uses, but there are several sort algorithms: Select sort, insert sort, and exchange sort. It is probably a quick sort.

A simple Java Problem

The sort method is in the Collections class and you have imported this class. However, if you call a method in another Class, you must use the Class name or object name to call the method. If you define the Sort method in your Class, you can call it directly using the method name.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.