The time complexity of Merge Sorting is: nlogn
It mainly uses two-way Merge Sorting, that is, to merge two sorted sets into one ordered set.
Below is a recursive binary merge sort I wrote.Algorithm:
Package algorithm; </P> <p> public class mergesort {<br/> // Private Static long sum = 0; </P> <p>/** <br/> * <PRE> <br/> * Two-way merge <br/> * principle: merge two ordered tables and one ordered table <br/> * </PRE> <br/> * @ Param A <br/> * @ Param S <br/> * Start subscript of the first ordered table <br/> * @ Param m <br/> * Start subscript of the second ordered table <br/> * @ Param T <br/> * ending small mark of the second ordered table <br/> */<br/> Private Static void merge (INT [], int S, int M, int t) {<br/> int [] TMP = New int [T-S + 1]; </P> <p> int I = s, j = m, K = 0; <br/> while (I <M & J <= T) {<br/> if (a [I] <= A [J]) {<br/> TMP [k] = A [I]; <br/> K ++; <br/> I ++; <br/>} else {<br/> TMP [k] = A [J]; <br/> // sum + = (J-I) -(J-m); <br/> J ++; <br/> K ++; <br/>}< br/> while (I <m) {<br/> TMP [k] = A [I]; <br/> I ++; <br/> K ++; <br/>}</P> <p> while (j <= T) {<br/> TMP [k] = A [J]; <br/> J ++; <br/> K + +; <Br/>}</P> <p> system. arraycopy (TMP, 0, A, S, TMP. length ); <br/>}</P> <p>/** <br/> * @ Param A <br/> * @ Param S <br/> * @ Param Len <br/> * length of the sorted set merged each time <br/> */<br/> Public static void mergesort (INT [], int S, int Len) {</P> <p> int size =. length; <br/> int mid = size/(LEN <1); <br/> int c = size & (LEN <1)-1 ); </P> <p> // ------- end the algorithm when only one sorted set is merged ------- // <br/> If (mid = 0) <B R/> return; </P> <p> // ------ sort by merging ------- // <br/> for (INT I = 0; I <mid; ++ I) {<br/> S = I * 2 * Len; <br/> Merge (A, S, S + Len, (LEN <1) + s-1 ); <br/>}</P> <p> // ------- merge the remaining number and the last order into ------- // <br/> If (C! = 0) <br/> Merge (A, size-C-2 * Len, size-C, size-1 ); <br/> // For (INT I = 0; I <. length; ++ I) {<br/> // system. out. print (A [I] + ""); <br/>//} <br/> // system. out. println (); </P> <p> // ------- recursively execute the next merge sort ------ // <br/> mergesort (A, 0, 2 * Len ); <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> // merge (New int [] {4, 3, 6, 1, 2, 5}, 0, 3, 5); </P> <p> int [] A = new int [] {4, 3, 6, 1, 2, 5 }; <br/> mergesort (A, 0, 1); </P> <p> for (INT I = 0; I <. length; ++ I) {<br/> system. out. print (A [I] + ""); <br/>}</P> <p> // system. out. println ("/N" + sum); <br/>}</P> <p>
Exercise: poj2299
However, it is best not to use recursion. I use recursion to report the RE, and then change it to non-Recursive Implementation to get rid of it!