Java Containers & generics: Four, Colletions.sort and Arrays.sort algorithms

Source: Internet
Author: User
Tags benchmark

Tell the map collection, or like to learn where to summarize it. Recent interview preparation, I was a member, the success of Ali online written test seconds to kill rebuffed. Normal Heart, continue to work hard. This brings the analysis of classical algorithms in collections and Arrays classes.

First, colletions and arrays

Collentions This class is completely a "wrapper" for the service container. Provides some action or a static method of returning a container. Arrays is a variety of methods used to manipulate arrays. Their link is in the Sort method, which is the topic of this blog.

Second, insert, fast, merge the basic algorithm

① Insert Sort

{A1},{a2,a3,a4,...,an}}

{{A1⑴,a2⑴},{a3⑴,a4⑴...,an⑴}}

...

{{a1 (n-1), A2 (n-1), ...},{an (n-1)}}

principle and Memory method: Each process is to compare the first element of the unordered sequence with the elements of an ordered sequence number, to find the insertion position, and insert the element into the proper position of the ordered series. This popular is the idea of finding seats. The Java version is implemented as follows

Importjava.util.Arrays; Public classinsertionsort{ Public Static voidMain (string[] args) {int[] IntA =New int[]{2,1,3,4,6,7,5};        System.out.println (arrays.tostring (IntA));        Insertionsort (IntA);    System.out.println (arrays.tostring (IntA)); }          Public Static voidInsertionsort (int[] a) {intP,right; inttemp;  for(p = 0; p < a.length; p++) {Temp=A[p]; /*** A[p] value to the left has a sequence comparison, inserted. */             for(right = p, right > 0 && a[right-1] > temp; right--) A[right]= A[right-1];//DisplacementA[right] =temp; }    }}

Right-click to run to see the console result:

[2, 1, 3, 4, 6, 7, 5][1, 2, 3, 4, 5, 6, 7]

② Quick Sort

The fast line is an algorithm based on the divide-and- conquer strategy , not a stable sorting algorithm, that is to say, the relative position of multiple identical values may change at the end of the algorithm. The Java version is implemented as follows:

 PackageJavabasic.algorithm;Importjava.util.Arrays; Public classquicksort{ Public Static voidMain (string[] args) {int[] IntA =New int[]{2,1,3,4,6,7,5};        System.out.println (arrays.tostring (IntA)); //Middlesort (IntA, 0, inta.length-1); //System.out.println (arrays.tostring (IntA));Sort (IntA, 0, Inta.length-1);    System.out.println (arrays.tostring (IntA)); }         //a partitioning process in fast sorting     Public Static intMiddlesort (intA[],intLeft,intRight ) {        inttemp = A[left];//as the number of intermediate axes         while(Left <Right ) {            /*** from right to left, find the first one smaller than the middle axis number, move to the left side*/             while(Left < right && A[right] >temp) Right--; A[left]=A[right]; /*** From left to right, find the first number larger than the middle axis, move to the right side*/             while(Left < right && A[left] <temp) left++; A[right]=A[left]; }                 /*** Assign the middle axis number to the value*/A[left]=temp; returnLeft ; }         //Quick Sort     Public Static voidSortint[] A,intLeftintRight ) {        if(Left <Right ) {            /*** Stop according to the same left and right index.             * Different words, according to the idea of divided treatment.             * Find the number of intermediate axes, split in half, etc. */            intMiddle =Middlesort (A, left, right); Sort (A, left, middle-1); Sort (A, middle+ 1, right); }    }     }

Memory method: Divide and conquer , is the division of labor. Here is a demonstration of the right points . A large number of empirical data surfaces, using two pivot to divide into 3 parts of the algorithm more efficient, this is dualpivotquicksort. This is the JDK source we are talking about later. Right-click and run to see the console and insert sort results.

③ Merge Sort

, from Baidu Encyclopedia. Merge sort is also a kind of algorithm of divide and conquer thought, it is not fast is the right point. Merging is an algorithm that is decomposed into merges . The following implementation methods:

 PackageJavabasic.algorithm;Importjava.util.Arrays; Public classmergesort{ Public Static voidMain (string[] args) {int[] IntA =New int[]{10,4,6,3,8,2,5,7};        System.out.println (arrays.tostring (IntA)); MergeSort (IntA,0,inta.length-1);    System.out.println (arrays.tostring (IntA)); }          Public Static voidMergeSort (int[] A,intLeft,intRight ) {        if(Left <Right ) {            intMiddle = (left + right)/2;//Intermediate IndexMergeSort (A, left, middle);//recursive to the left arrayMergeSort (A, middle+1, right);//recursive to the right arraymerge (a,left,middle,right);//Merge Algorithm        }    }     Private Static voidMergeint[] A,intLeftintMiddle,intRight ) {        int[] Tmparr =New int[A.length]; intMID = Middle+1; intTmparrleft = left;//records the index of the left array        intTmpleft =Left ; /*** Remove a small portion from two arrays to copy*/         while(Left <= Middle && mid <=Right ) {            if(A[left] <=A[mid]) tmparr[tmparrleft+ +] = a[left++]; ElseTmparr[tmparrleft+ +] = a[mid++]; }                 /*** Copy to the right of the remaining part*/         while(Mid <=Right ) {Tmparr[tmparrleft+ +] = a[mid++]; }                 /*** Left copy of remaining part*/         while(Left <=middle) {Tmparr[tmparrleft+ +] = a[left++]; }                 /*** Split the re-fit*/         while(Tmpleft <=Right ) {A[tmpleft]= tmparr[tmpleft++]; }    }     }

The result is the same:

[4, 6, 3, 8, 2, 5, 7] [2, 3, 4, 5, 6, 7, 8, 10]
Third, the number of JDK

In this thank you @ Jiangnan White Brother's article, I help very much. The following are referenced:

 5. Jdk7/8 interview season, the students back a head of the insertion, merging, bubbling, quick row, then, the JDK exactly what kind of sorting algorithm? Colletions.sort (list) and Arrays.sort (t[]) colletions.sort () actually convert the list to an array, then call Arrays.sort (), and then go back to list. and Arrays.sort (), the original type ( int  [],double  [],char  [],byte  []), JDK6 is used for quick sorting, for object type (object[]), and JDK6 uses merge sort. Why use a different algorithm? JDK7 's progress to the JDK7, quick sort upgrade to double benchmark fast row (double benchmark Fast vs. three-way fast); Merge sort upgrade to merge sort of improved version timsort, a JDK self-evolution. JDK8 's progress went to JDK8, adding the Arrays.parallelsort () function to the large collection, using fork -join frame, taking full advantage of multicore, The large collections are sliced and then sorted, and in small contiguous fragments, timsort and Dualpivotquicksort are still used. Conclusion the efforts of the JDK team are not visible from some simple new Features /change List, so it's OK to upgrade the JDK 

I've also looked at the algorithms for tracking to the Dualpivotquicksort class, but this class is not in the JDK API. (Throw a question : Why does this class not appear in the API?) Haha, a look at the author is the father of Java involved in writing, a moment of research passion. According to Big Brother White, quick sort is sorted by double datum to three quick sort. It is also more efficient to divide the algorithm into 3 parts using two pivots on a large number of empirical data surfaces. The idea of arithmetic is also divided and governed.

The following is a comment on a person's introspection:

/*** If The length of an array to be sorted are less than this * constant, Quicksort are used in preference to merge    Sort.    * When the array length is less than 286, why is quick sorting better than the merge sort? */   Private Static Final intQuicksort_threshold = 286; /*** If The length of an array to be sorted are less than this * constant, insertion sort was used in preference to    Quicksort.    * When the array length is less than 47, why is the insertion sort better than the quick sort? */   Private Static Final intInsertion_sort_threshold = 47;

Why? Second question, welcome to the great God answer.

My understanding: First, build on a lot of empirical data results. Second, according to the algorithm time complexity and space complexity. As for in-depth understanding needs great God solution.

The JDK sort order diagram is as follows:

Reprinted from: http://www.bysocket.com/?p=219

Java Containers & generics: Four, Colletions.sort and Arrays.sort algorithms

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.