Merge sort idea: Sort an array into two parts (using recursion), then merge the results together, merging the last two ordered arrays into a larger ordered array.
Time complexity o (n) = Nlogn
The most appealing nature of merge sorting is that it guarantees that the time required to sort an array of any length n is proportional to the nlogn, and the disadvantage is that the extra space required is proportional to n.
Merge sort is also divided into top-down sorting and bottom-up sorting methods:
The top-down ranking method uses the idea of divide and conquer, and divides a big problem into several equivalent sub-problems to solve.
The bottom-up is sorted by merging the micro arrays and then merging the resulting sub-arrays.
The code for the two sorting methods is as follows:
/** * * @author seabear * */public class MergeSort {private static comparable[] b;p ublic static Boolean less (comparable V,comparable W) {return V.compareto (W) < 0;} public static void Merge (comparable[] a,int lo,int mid,int hi) {int i = Lo;int J = mid + 1;for (int k = lo; k < hi + 1; k + +) {B[k] = a[k];} for (int k = lo; k < hi + 1; k++) {if (i > Mid) {a[k] = b[j++];} else if (J > Hi) {a[k] = b[i++];} else if (less (b[i],b[j])) {A[k] = b[i++];} ELSE{A[K] = b[j++];}} /** * top-down and bottom-up * @param a */public static void sort (comparable[] a) {b = new comparable[a.length];//top-down//sort (A,0,a.leng TH-1);//Bottom up for (int i = 1; i < a.length; i = i + i) {for (int lo = 0; lo < a.length-i; Lo + = i + i) {merge (A, lo, lo + i-1, Math.min (lo + i + i-1, a.length-1));}}} public static void Sort (comparable[] a,int lo,int hi) {if (Hi <= lo) {return;} int mid = lo + (hi-lo)/2;sort (A,lo,mid); sort (a,mid + 1,hi); merge (A,lo,mid,hi);} public static void Show (comparable[] a) {for (int i = 0; i < a.length;i++) {System.out.print (A[i] + "");} System.out.println ();} public static void Main (string[] args) {integer[] a = new Integer[10];for (int i = 0; i <; i++) {a[i] = (int) (Math.rand Om () * 10 + 1);} Show (a); sort (a); show (A);}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm (fourth edition) Java implementation of learning notes merge sort