"Merge" means to combine two or more ordered tables into a new ordered table. Both sequential storage and linked list storage structures can be implemented at O (m + n) Time level.
Merge Sorting is another type of sorting method. Assuming that the initial sequence contains N records, it can be considered as N ordered subsequences. The length of each subsequence is 1, and then the two are merged, obtain n/2 ordered subsequences of 2 or 1, and merge them into two or two ,......., this is repeated until an ordered sequence with a length of N is obtained.
Initial Keyword: [49] [38] [65] [97] [76] [13] [27]
A a B C c d
After one merge: [38 49] [65 97] [13 76] [27]
A A B
After merge: [38 49 65 97] [13 27 76]
A
After merging three trips: [13 27 38 49 65 76 97]
The preceding example shows a typical application of the merge sort algorithm.
Implementation example (C language description ):
void Merge(ElementType array[], ElementType TmpArray[], int lpos, int rpos, int rightend){if(array == NULL || TmpArray == NULL)return;int i, leftend, numelements, tmppos;leftend = rpos - 1;tmppos = lpos;numelements = rightend - lpos + 1;/*main loop*/while(lpos <= leftend && rpos <= rightend)if(array[lpos] <= array[rpos])TmpArray[tmppos++] = array[lpos++];elseTmpArray[tmppos++] = array[rpos++];while(lpos <= leftend)TmpArray[tmppos++] = array[lpos++];while(rpos <= rightend)TmpArray[tmppos++] = array[rpos++];for(i = 0; i < numelements; i++, rightend--)array[rightend] = TmpArray[rightend];}void MSort(ElementType array[], ElementType TmpArray[], int left, int right){if(array == NULL || TmpArray == NULL || left < 0 || right < 0)return ;int center;if(left < right){center = (left + right) / 2;MSort(array, TmpArray, left, center);MSort(array, TmpArray, center + 1, right);Merge(array, TmpArray, left, center + 1, right);}}void Mergesort(ElementType array[], int length){if(array == NULL || length < 0)return;ElementType *TmpArray;TmpArray = (ElementType *)malloc(length * sizeof(ElementType));if(TmpArray == NULL){fprintf(stderr, "no space.\n");return;}MSort(array, TmpArray, 0, length - 1);free(TmpArray);return;}
From the implementation of the algorithm given above, we can see that the time complexity is O (nlogn) for implementing the number of auxiliary spaces required for merging and sorting and waiting for records ). Compared with fast sorting and heap sorting, Merge Sorting is a stable sorting method. In addition, the Merge Sorting method mentioned above uses the recursive method. The recursive form is relatively simple, but its practicality is very poor. Implement the recursive algorithm in the form of user fees.
References:
1. Data Structure and algorithm analysis-C language description by Mark Allen Weiss
2. Edited by Yan Weimin Wu Weidong, data structure (C language description)
3. http://blog.csdn.net/to_be_it_1/article/details/37866391
4. http://blog.csdn.net/morewindows/article/details/6671824
Sort algorithms for algorithm learning: Merge Sorting