Java merge sort, single thread vs multithreading

Source: Internet
Author: User

First, what is the merge sort

Merge sort, also known as merging sort, is a perfect example of successful application of divide-and-conquer technology. For a sort of array a[0..n-1], merge sort divides it into two: a[0..n/2-1] and a[n/2..n-1], and recursively sorts each sub-array, then merges the two sorted sub-arrays into an ordered array. The following is an example of a merge sort diagram:

Second, single-threaded implementation of merge sort
 PackageCom.bob.algorithms.sort;Importjava.util.Arrays;ImportCom.bob.algorithms.SortStrategy;/*** Merge Sort * *@authorBob **/ Public classSinglethreadmergesortImplementsSortstrategy { Public int[] Sort (int[] rawarray)        {mergesort (Rawarray); returnRawarray; }    /*** Split and merge sort, ascending * *@paramIntarr*/    Private voidMergeSort (int[] intarr) {        if(Intarr.length > 1) {            //if the array length is greater than 1, the decomposition is called two copies            int[] Leftarray = Arrays.copyofrange (intarr, 0, INTARR.LENGTH/2); int[] Rightarray = Arrays.copyofrange (Intarr, INTARR.LENGTH/2, intarr.length);            MergeSort (Leftarray);            MergeSort (Rightarray); //Merge and Sortmerge (Leftarray, Rightarray, intarr); }    }    /*** Merge Sort * *@paramLeftarray *@paramRightarray *@paramIntarr*/    Private voidMergeint[] Leftarray,int[] Rightarray,int[] intarr) {        //I:leftarray array index, J:rightarray array index, K:intarr array index        inti = 0, j = 0, k = 0;  while(I < leftarray.length && J <rightarray.length) {//when there are values in all two arrays, compare the current element for selection            if(Leftarray[i] <Rightarray[j]) {Intarr[k]=Leftarray[i]; I++; } Else{Intarr[k]=Rightarray[j]; J++; } k++; }        //append the remaining elements to the intarr immediately after the array is not traversed        if(i = =leftarray.length) { for(; J < Rightarray.length; J + +, k++) {Intarr[k]=Rightarray[j]; }        } Else {             for(; i < leftarray.length; i++, k++) {Intarr[k]=Leftarray[i]; }        }    }}

Third, using Fork/join framework to achieve merge sort

Fork/join is a concurrent computing framework that is added from JDK 1.7.

 PackageCom.bob.algorithms.sort;Importjava.util.Arrays;ImportJava.util.concurrent.ForkJoinPool;Importjava.util.concurrent.RecursiveAction;ImportCom.bob.algorithms.SortStrategy; Public classForkjoinmergesortImplementsSortstrategy { Public int[] Sort (int[] rawarray) {Forkjoinpool Pool=NewForkjoinpool (); Pool.invoke (Newmergesort (Rawarray)); returnRawarray; }    /*** Merge sort using Fork/join, make full use of CPU * *@authorZhangwensha **/    Private Static classMergeSortextendsrecursiveaction {Private Static Final LongSerialversionuid = 425572392953885545L; Private int[] intarr;  PublicMergeSort (int[] intarr) {             This. Intarr =intarr; } @Overrideprotected voidCompute () {if(Intarr.length > 1) {                //if the array length is greater than 1, the decomposition is called two copies                int[] Leftarray = Arrays.copyofrange (intarr, 0, INTARR.LENGTH/2); int[] Rightarray = Arrays.copyofrange (Intarr, INTARR.LENGTH/2, intarr.length); //here is divided into two parts of the executionInvokeAll (NewMergeSort (Leftarray),Newmergesort (Rightarray)); //Merge and Sortmerge (Leftarray, Rightarray, intarr); }        }        /*** Merge Sort * *@paramLeftarray *@paramRightarray *@paramIntarr*/        Private voidMergeint[] Leftarray,int[] Rightarray,int[] intarr) {            //I:leftarray array index, J:rightarray array index, K:intarr array index            inti = 0, j = 0, k = 0;  while(I < leftarray.length && J <rightarray.length) {//when there are values in all two arrays, compare the current element for selection                if(Leftarray[i] <Rightarray[j]) {Intarr[k]=Leftarray[i]; I++; } Else{Intarr[k]=Rightarray[j]; J++; } k++; }            //append the remaining elements to the intarr immediately after the array is not traversed            if(i = =leftarray.length) { for(; J < Rightarray.length; J + +, k++) {Intarr[k]=Rightarray[j]; }            } Else {                 for(; i < leftarray.length; i++, k++) {Intarr[k]=Leftarray[i]; }            }        }    }}

 
Four, single-thread PK multi-threaded

The stage class was written and the length of the array to be sorted was set by adjusting the input parameters of Generateintarray (10000000), and the heap capacity was not set in the experiment.

 Packagecom.bob.algorithms;Importjava.util.Arrays;Importjava.util.Date;ImportCom.bob.algorithms.common.CommonUtil;ImportCom.bob.algorithms.sort.ForkJoinMergeSort;ImportCom.bob.algorithms.sort.SingleThreadMergeSort;/*** Stage class, which is designed to test the algorithm time * *@authorBob **/ Public classStage { Public Static voidMain (string[] args) {//variable definition        LongBeginTime = 0; LongEndtime = 0; //Generate sort Data        int[] Rawarr = Generateintarray (10000000); int[] rawArr2 =arrays.copyof (Rawarr, rawarr.length); BeginTime=NewDate (). GetTime (); NewSinglethreadmergesort (). sort (Rawarr); //System.out.println (arrays.tostring (New Singlethreadmergesort (). Sort (Rawarr)));Endtime =NewDate (). GetTime (); System.out.println ("Single thread merge sort takes time:" + (Endtime-begintime)); System.out.println ("Whether ascending:" +commonutil.issorted (Rawarr,true)); BeginTime=NewDate (). GetTime (); NewForkjoinmergesort (). sort (RAWARR2); //System.out.println (arrays.tostring (New Forkjoinmergesort (). Sort (RAWARR2)));Endtime =NewDate (). GetTime (); System.out.println ("Fork/join merge sort takes time:" + (Endtime-begintime)); System.out.println ("Whether ascending:" +commonutil.issorted (RAWARR2,true)); }    /*** Generate an array of type int * *@return     */    Private Static int[] Generateintarray (intlength) {        int[] Intarr =New int[length];  for(inti = 0; i < length; i++) {Intarr[i]=NewDouble (Math.random () *length). Intvalue (); }        returnintarr; }}

 

The following are the efficiency comparisons of the two methods when the array capacity is at each magnitude:

- +
Array Length 10000 100000 1000000 10000000
Single Thread (MS) 1 2 7 33 188 2139
Fork/join (MS) 8 9 17 63 358 1133

Statistics show that, when the sequence length is small, the use of single-threaded efficiency is higher than multi-threading, but as the number continues to increase, multithreaded execution time is closer to single-threaded execution time, and finally at 10 million, the magnitude of the start rate is far more than a single thread. It is not possible to abuse multi-threading at work, which can speed up efficiency and make full use of multicore when used. But when it is not possible to use the increase in workload, it may not be as efficient as a single thread. Interested friends can use the code address below to find running all the source of their own run to try to run.

Five, the code address of this article

Including this post, all code is stored in the following uniform address:
Https://github.com/mingbozhang/algorithm

Vi. references

Https://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
Fundamentals of algorithmic Design and Analysis (3rd edition)

Java merge sort, single thread vs multithreading

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.