Thought:
assuming the initial sequence rightNRecords, the first of theseNa record asNordered subsequence, each sub-sequence has a length of1, and then 22 merge, GetN/2Rounding up a length of2(Nis odd, the length of the last sequence is1) ordered sub-sequences. On this basis, the length of the2the ordered sub-sequences of 22 are merged to get several lengths of4ordered sub-sequences. So repeat until you get a length ofNordered sequence.
Stability: Stable
Calculation of time complexity:
The size of the array is a power of 2, so that it can always be divisible by 2. Assume a K-square of 2, or K=LOG2 (n).
Each time we select a value that is exactly the median, the array can be divided equally.
The first layer recursion, need to loop n times to sort well, the second layer of cyclic (N/2) ...
So there are n+2 (N/2) +4 (N/4) +...+n* (n/n) = N+N+N+...+N=K*N=LOG2 (n) *n
So the algorithm complexity is O (log2 (n) *n).
Code:
public static void sort (int[] data, int left, int right) { system.out.println (left+ ":" +right); if (left < right) { int center = (left + right) / 2; system.out.println (left+ ":" +center+ ":" +right); // recursively sort the left array ( Data, left, center); system.out.println (left+ ":" +center+ ":" +right ); // recursive sort (data, center + 1, right) to the right array; // merged merge (data, left, center, right ); } } public static void merge (int[] data, int left, Int center, int right) { int[] tmparr = new int[data.length ]; int&nbSp;mid = center + 1; // third records the index of an intermediate array int third = left; int tmp = left; while (left <= center && mid <= right) { // Remove the smallest of the two arrays into the middle array if (Data[left] <= data[mid]) { tmparr[third++] = data[ left++]; } else { tmparr[third++] = data[mid++]; The remainder of the } } // is placed in the middle array in turn while (mid <= right) { tmpArr[third++] = data[mid++]; } while ( Left <= center) { tmparr[third++] = data[left++]; } // Copy the contents of the intermediate array back to the original array while (tmp <= right) { data[tmp] = Tmparr[tmp++]; } system.out.println (arrays.tostring (data)); } public static void main (String[] args) { int[] a1 = {5,1,3,4,2}; sort (a1,0,a1.length-1); }
Data structure Merge sort Java implementation