Basic ideas
The sequence of elements to be sorted is first divided into two sub-sequences of equal length, sorted for each subsequence, and then merged into a sequence.
Code
Private void MergeSort(int[] A,int[] B,intLeftintright) {if(Left < right) {intMiddle = (left + right)/2; MergeSort (A, B, left, middle); MergeSort (A, B, Middle +1, right); Merge (A, B, left, middle, right); }}Private void Merge(int[] A,int[] B,intLeftintMiddle,intright) {if(Left < right) {intP, q, t; p = left; Q = middle +1; T = left; while(P <= Middle && Q <= right) {if(A[p] <= a[q]) {b[t++] = a[p++]; }Elseb[t++] = a[q++]; } while(P <= middle) b[t++] = a[p++]; while(q <= right) b[t++] = a[q++]; for(intK = left; K < T; k++) A[k] = b[k]; }}
Performance analysis
- Complexity of Time
The time required for two-way merge sorting mainly includes the time of dividing two sub-sequences, the time of sorting the two sub-sequences and the merging time respectively. The time to divide the sub-sequence is a changshu, can not be considered, the last time required to merge with the number of elements n linear correlation, therefore, for a length of n sequence of elements to merge the time cost is T (N)=CN+2T (N/2) 。 Since the merge sort does not depend on the initial input arrangement of the original ordered element sequence, the length of the two subsequence is basically the same at each partition, so the best, worst, and average time complexity of the merge sort is O(NLo g 2 N) 。
- Complexity of space
It requires a secondary space as large as the original array to be sorted.
- Stability
Merge sort is a kind of stable sorting algorithm.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Two-way merge sort of sorting algorithm