# Merge and Merge sort

Source: Internet
Author: User

1. Merge Operation : Is the process of merging two ordered and independent files into an ordered file.
2. Merge sort : In contrast to the fast sort process, it is a merge process after two recursive calls (sort sub-files).
When sorting quickly, it is the process of two recursive calls (sort sub-files) that are decomposed into two sub-problems first.

• Merge operations
• 1 Basic two-way merge
• 2 abstract in-situ merging
• Merge sort
• 1 Top-down merge sort
• 2 Bottom-up merge sort
• 3 Performance characteristics of merge sort
• Linked list implementation with merge sort
• Merge sort and Quick sort comparison

1. Merge Operation 1.1 Basic two-way merge

Merges two ordered arrays A and b into an ordered array of C.
The process of merging operations is as follows:
1. Apply the space so that it is the sum of two sorted sequences that are used to store the merged sequence
2. Set two pointers, the initial position is the starting position of two sorted series
3. Compare the elements pointed to by two pointers, select a relatively small element into the merge space, and move the pointer to the next position
4. Repeat step 3 until a pointer reaches the end of the sequence
5. Copy all remaining elements of another sequence directly to the end of the merge sequence

``//Combine an ordered array, A and B into an ordered array CvoidMergeAB0 (item c[], item a[],intM, Item b[],intN) {intK =0;inti =0, j =0; while(K < M+n) {if(i = = M)//a Array is ended{c[k++] = b[j++];Continue; }if(j = = N)//b Array is ended{c[k++] = a[i++];Continue; }if(Less (A[i], b[j])) c[k++] = a[i++];Elsec[k++] = b[j++]; }}``

This merge is stable, and it maintains the relative order of the same keywords.

1.2 Abstract in-situ merging

Target: Combine the array a[l],......, a[m] and a[m+1],......, A[r] into an ordered file, the result is saved in A[l],......, a[r].

Implementation: By constructing a bidirectional sequence (bitonic order), the test operation in 1.1 is omitted to check whether the tail of the array is reached .
Copies the first array to the secondary array aux[] and copies the second array to the aux[] in reverse order immediately following the first array. The first for loop moves the first array so I points to L, and the second for moves the second array, so that J points to R and prepares for the merge. Then, in the merge operation (the third for), the largest element is treated as an observation post, regardless of which array it is in.

``//abstract in-situ merge algorithm: Merge algorithm for bidirectional sequences, unstable   Mergeab (Item a[], int  L, int  m, int  r) {//build bidirectional sequence  int  I, j, K; for  (i = M+1 ; i > L; i--) Aux[i-1 ] = A[i-1 ]; for  (j = m, k = R; J < R; j + +, k--) aux[k] = A[j+1 ]; //merge operation; At this point, i=l,j=r  for  (k = l; k <= R; k++) {if  (Less (Aux[i], aux[j])) a[k] = aux[i++]; else  a[k] = aux[j--]; }}``

This merge is not stable.

2. Merge sort

Divide and Conquer strategy (1) decompose the original file into 2 sub-files of equal size, (2) Sort 2 sub-files separately; (3) Merge 2 ordered sub-files

2.1 Top-down merge sort
``//自顶向下的merge sortvoidintint r){    if(l >= r)        return;    //小文件改进    // if(r-l < 10) {insertion_sort(a, l, r); return;}    int m = (l+r)/2;    merge_sort(a, l, m);    merge_sort(a, m+1, r);    mergeAB(a, l, m, r);}``

Algorithm Analysis
(1) For files of length n, you need to lgN (Depth of the tree) the two-way merge, the time of each merger is O(N) , so its time complexity, whether in the best case or in the worst case, is O ( n l g n ) 。
(2) An auxiliary array is required to stage the result of merging two ordered sub-files, so its auxiliary space complexity is O(N) , obviously it is not in-place sort.
(3) If the merging algorithm used is stable, the sorting algorithm is stable.

2.2 Bottom-up merge sort

Each recursive program has a non-recursive program corresponding to it.
principle : First find out the solution of small problem, combine it into the solution of larger problem.
(1) Consider all the elements in the file as an ordered sub-table of size 1, and then facilitate the 1-1 merging of these tables, resulting in an ordered sub-table of size 2;
(2) then traverse the file list for 2-2 merges, resulting in an ordered sub-table of size 4
(3) then 4-4 merges, producing an ordered sub-table of size 8, and so on, until the entire table is ordered

By merging the m-m in the entire file, the bottom-up merge sort is done, and M doubles in each pass; only if the file size is an even multiple of M, the size of the last sub-file is M, otherwise the final merge is m-x merge, x <= m

``//自底向上 merge_sortvoidintint r){    int i, m;    for12//控制每层子问题的大小    {        for2//从最左侧，依次递增 2m            mergeAB(a, i, i+m-1min(i+2*m-1, r));     }}``

Property 1:Except for the last child file, the size of all child files is a power of 2,
Property 2:The number of times that the bottom-up merge sort of n elements is executed is K, which is the 2 k >= N The minimum value established, i.e. lgN , and N is the number of bits represented by the binary.

2.3 Performance characteristics of merge sort

Run time and l g n is proportional to the input and is irrelevant;
can be implemented stably.

3 Merge sorted list Implementation 4 Merge sort and quick sort comparison
1. Recursive implementation: Fast sorting, in a recursive implementation, most of the work (partitioning process) is done before recursive recursive invocation, whereas the merge sort is after recursion.
2. Non-recursive implementation: The fast sort must use the stack, because it holds a large sub-problem, and then decomposition according to the data, and the partition of the merge sort is irrelevant to the data.
3. Stability: Stable merge operation, can guarantee stable merge sort; for fast array-based sorting, it is not easy to divide the array stably, and the stability is destroyed before recursion, but the fast ordering based on the list is stable.

Merge and Merge sort

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.