The time complexity of the merge sort is: Nlogn
The main is to use the two-way merge sort, that is, two ordered sets are merged into an ordered set.
Here's a recursive two-way merge sort algorithm that I wrote:
Package algorithm; public class MergeSort {//private static long sum = 0;/** * <pre> * Two-way merge * Principle: Combine two ordered tables with an ordered table * </pre> * * Param A * @param s * The starting subscript * of the first ordered table * @param m * The beginning subscript of the second ordered table * @param T * The end of the second ordered table */private static void merge (int[] A, int s, int m, int t) {int[] tmp = new int[t-s + 1]; int i = s, j = m, k = 0; while (i < m && J <= T) {i F (A[i] <= a[j]) {tmp[k] = a[i]; k++; i++;} else {tmp[k] = a[j];//Sum + = (j-i)-(j-m); j + +; k++;} while (I < m) {Tmp[k] = A[i]; i++ k++;} while (J <= t) {tmp[k] = A[j]; j + +; k++;} System.arraycopy (TMP, 0, a, s, tmp.length); /** * * @param A * @param s * @param len * The length of the ordered set per merge/public static void MergeSort (int[] A, int s, int len) {int S ize = A.length; int mid = size/(len << 1); int c = size & ((len<<1)-1); -------Merge to an ordered set when the end algorithm-------//if (mid = = 0) return; ------A Merge sort-------//for (int i = 0; i < mid; ++i) {s = i * 2 * len; Merge (A, S, S + len, (len << 1) + s-1); //-------Merge the remaining number and the penultimate order set-------/if (c!= 0) merge (A, size-c-2 * len, size-c, size-1); for (int i = 0; i < a.length ++i) {//System.out.print (A[i] + ""); }//System.out.println (); -------recursively perform the next merge sort------//mergesort (A, 0, 2 * len); public static void Main (string[] args) {//merge (new int[] {4, 3, 6, 1, 2, 5}, 0, 3, 5); int[] A = new int[] {4, 3, 6, 1, 2, 5}; MergeSort (A, 0, 1); for (int i = 0; i < a.length ++i) {System.out.print (A[i] + ""); System.out.println ("n" + sum); } }
Practice: poj2299
But this problem, it is best not to use recursion, I use the recursive report re, later changed to the implementation of a recursive, just a off, hehe.