1. The principle of merge sorting:
Principle, the original array is divided into several sub-arrays, each sub-array is sorted,
Continue to merge the array with the sub-arrays, and the merge remains orderly until all are merged, forming an ordered array
Example:
Unordered Array [6 2 4 1 5 9]
Look at the status of each step, and then look at the merge details.
First step: [6 2 4 1 5 9] original state
Step Two: [2 6] [1 4] [5 9] 22 merge Sort, sort details behind introduction
Step three: [1 2 4 6] [5 9] Continue two groups of merging
Fourth step: [1 2 4 5 6 9] Merge complete, sort complete
Output result: [1 2 4 5 6 9]
2. Merge Sort Code implementation:
1 PackageCn.itcast;2 3 /*4 * Merge operation (merge), also called merge algorithm, refers to the operation of merging two sorted sequences into a sequence. 5 * If there is a series {6,202,100,301,38,8,1}6 * Initial state: [6] [202] [100] [301] [38] [8] [1] comparison times7 * I=1 [6 202] [301] [8] [1] 38 * i=2 [6 202 301] [1 8] 49 * i=3 [1 6 8 202 301] 4Ten */ One Public classMergeSort { A Public Static voidSortint[] data) { - int[] temp =New int[data.length]; -MergeSort (data, temp, 0, data.length-1); the } - - Private Static voidMergeSort (int[] Data,int[] temp,intLintr) { - intMid = (L + r)/2; + if(L = =R) - return; + mergesort (data, temp, l, mid); AMergeSort (data, temp, MID + 1, R); at - for(inti = l; I <= R; i++) { -Temp[i] =Data[i]; - } - intI1 =l; - intI2 = mid + 1; in for(intcur = l; Cur <= R; cur++) { - if(I1 = = Mid + 1) toData[cur] = temp[i2++]; + Else if(I2 >R) -Data[cur] = temp[i1++]; the Else if(Temp[i1] <Temp[i2]) *Data[cur] = temp[i1++]; $ ElsePanax Notoginseng -Data[cur] = temp[i2++]; the } + } A}
Java Fundamentals Hardening 56: Merging and sorting of classical algorithms (mergesort)