First, merge sortMerge sort is an effective sorting algorithm based on merging operation, which is a typical application of Divide and conquer by divide-and-conquer method. The ordered Subsequence is merged to get a completely ordered sequence. That is, the sequence of each subsequence is ordered first. And then order the sub-sequences between segments. If you combine two ordered tables into an ordered table. Called Two-way merge. The merging process is: compare A[i] and a[j] size. If A[I]≤A[J], the element in the first ordered table A[i] is copied to r[k], and I and K are added 1 respectively. Otherwise, copy the elements in the second ordered table A[j] to r[k] and add 1 to J and K respectively. So cycle down. Until one of the ordered tables is finished, the remaining elements in an ordered table are then copied to the cells in R from subscript K to subscript t. Merging sorting algorithm we often use recursive implementation, first to sort the interval [s,t] to the midpoint of the two points, then the left sub-range, then the right sub-interval, and finally the left and right intervals with a merge operation into an orderly interval [s,t].
Second, merge operation
three, two-way merging algorithm 1. Basic idea of Algorithm
set two ordered sub-files (equivalent to the input heap) placed in the same vector adjacent to the position: R[low. M],r[m+1..high]. Merge them into a local staging vector R1 (equivalent to the output heap) and copy the R1 back to R[low when the merge is complete. High].
(1) Merger process
During the merge process, set the I,J and p three pointers. The initial value points to the starting position of the three record areas respectively.
Merge R[i] and r[j] keyword, take keyword smaller records to r1[p], then copy the recorded pointer I or J plus 1, and pointer to the copy position p plus 1.
Repeat this process until the two input sub-files have a copy of all of the completed (preferably called empty), at this point, there will be a non-empty sub-file in order to copy the remaining records to R1.
(2) Dynamic application R1
When implemented. R1 is a dynamic application. Because the space for the application can be very large. Therefore, it is necessary to increase the successful processing of the application space.
2. Merging algorithm
void Merge (Seqlist r,int Low. int M,int High) {//will be two ordered sub-files R[low: m) and R[m+1..high] Merge into an ordered //sub-file R[low. High] int i=low,j=m+1,p=0;//Set initial value RecType *r1;//r1 is local vector. If the P definition is faster for this type of pointer r1= (REETYPE *) malloc ((high-low+1) *sizeof (RecType)). if (! R1)//Application space failure Error ("Insufficient Memory available!"). while (I<=m&&j<=high)//Two sub-files are not empty when they are output to r1[p] r1[p++]= (R[i].key<=r[j].key)? R[i++]:r[j++]. while (i<=m)//If the 1th sub-file is not empty, copy the remaining records into R1 r1[p++]=r[i++]. while (J<=high)//If the 2nd sub-file is not empty, copy the remaining records into R1 R1[p++]=r[j++]. For (P=0,i=low;i<=high. p++. i++) r[i]=r1[p];//The results back to R[low when the merge is complete. High] }//merge
Iv. Merging and sorting
There are two ways to achieve merge sorting: bottom-up and top-down. Here's the word.
top-down approach
Span style= "font-size:18px" > (1) Three steps to divide the method
Set the current interval for merge sort is r[low. High], the three steps of the divide-and-conquer method are:
① decomposition: Split the current interval in two, i.e. splitting point
② Solver: Recursively to two sub-bands R[low. Mid] and R[mid+1..high] are sorted by merge.
③ Combination: Two sub-bands sorted R[low ... Mid] and R[mid+1..high] are merged into an ordered interval r[low. High].
Recursive termination condition: The sub-interval length is 1 (a record is naturally ordered).
(2) detailed algorithm
void Mergesortdc (Seqlist r,int Low. int high) {//Divide and conquer the R[low. High] for two-way merge sort int Mid, if (low
(3) The running process of algorithm MERGESORTDC
The algorithm MERGESORTDC The running steps for example with the seen recursive tree.
Five, algorithm analysis
1. Stability
Merge sort is a stable sort.
2. Storage structure Requirements
The available sequential storage structure. It is also easy to implement on a linked list.
3. Complexity of Time
For files of length n, a two-way merge is required, and the time to merge is O (n) per trip. Therefore, the time complexity is O (NLGN) in both the best and worst cases.
4. Complexity of space
A secondary vector is required to stage the result of merging two ordered sub-files. Therefore, its auxiliary space complexity is O (n). Obviously it's not an in-place sort.
Note:
If you are using a single-linked list for the storage structure. Very easy gives the in-place merge sort.
5, compare the number of operations between (NLOGN)/2 and Nlogn-n + 1.
6, the number of assignment operations is (2NLOGN). The spatial complexity of the merge algorithm is: 0 (n)
7, merge sort is more memory-intensive. But it is a high efficiency and stable algorithm.
VI, code implementation
public class Mergesorttest {public static void main (string[] args) {int[] data = new int[] {2, 4, 7, 5, 8, 1, 3, 6}; System.out.print ("Initialize: \ T");p rint (data); System.out.println (""); mergesort (data, 0, data.length-1); System.out.print ("\ n sort: \ t");p rint (data);} public static void MergeSort (int[] data, int left, int. right) {if (left >= right) return;//two-way merge//find Intermediate index int center = (le FT + right)/2;//recursive mergesort (data, left, center) for the array on the right,//recursive mergesort (data, center + 1, ") for the array on the rights,//merge the merge (data, Left, center, center + 1, right); System.out.print ("in order: \ T");p rint (data);} /** * Merges two arrays. Merging the first 2 arrays is ordered. The merge is still orderly * * @param data * Array Object * @param leftstart * Index of the first element of the left array * @param leftend * The left array Index of the last element * @param rightstart * Index of the first element of the right array * @param rightend * Index of the last element of the right array */public static void me Rge (int[] data, int leftstart, int leftend,int rightstart, int rightend) {int i = Leftstart;int j = Rightstart;int k = 0;/ /temporary array int[] temp = new Int[riGhtend-leftstart + 1]; Create a temporary array to hold the array that is temporarily sorted//confirm that the two-segment array after the cut is taken to the last element while (I <= leftend && J <= rightend) {//Remove the smallest from two arrays into a temporary array I F (Data[i] > Data[j]) {temp[k++] = data[j++];} else {temp[k++] = data[i++];}} The remainder is put into a temporary array (actually two while only one is running) while (I <= leftend) {temp[k++] = data[i++];} while (J <= rightend) {temp[k++] = data[j++];} K = leftstart;//Copies the contents of the temporary array back to the original array//(the contents of the original Left-right range are copied back to the original array) for (int element:temp) {data[k++] = element;}} public static void print (int[] data) {for (int i = 0; i < data.length; i++) {System.out.print (data[i] + "\ t");} System.out.println ();}}
vii. Results of implementation
Initialization: 24758136 sorted in: 24758136 sorted: 24578136 sorted in: 24578136 sorted: 24571836 sorted in: 24571836 sorted in: 24571368 sorted in: 12345678 after sorting: 12345678
==================================================================================================
Ouyangpeng Welcome reprint. Sharing with others is the source of progress!
Reprint please keep the original address : Http://blog.csdn.net/ouyang_peng
==================================================================================================
watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvb3v5yw5nx3blbmc=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "style=" border:none; max-width:100%; font-size:24px; line-height:24px; Text-indent:2em ">
My Java Development learning journey------> Merge sort of Java classic sorting algorithm