Merge Sorting
Merging: combines two or more ordered sequences into an ordered sequence. If linear tables are used (regardless of the storage structure), the time complexity is O (m + n ).
Examples of merging ideas: the two groups of playing cards are sorted in ascending order. They need to be merged into a pile and sorted in ascending order.
◆ Extract the top two stacks (set to C1, C2) to compare the size, and place the small ones on one side as a new heap (You may wish to set C1 ◆ Repeat the above process until a pile has been drawn, and then all the cards in the remaining pile are transferred to the new stack.
1. Sort ideas
① When each record is regarded as a separate ordered sequence, n to be sorted records are n ordered subsequences with a length of 1;
(2) Merge all ordered subsequences to obtain an ordered subsequence with a length of 2 or 1, namely, ''n'/2;
③ Repeat ② until an ordered sequence with a length of n is obtained.
In the above sorting process, the sub-sequences are always merged, which is called the 2-way merge sorting. The core is how to merge two adjacent subsequences into a subsequence. Set two adjacent subsequences as follows:
{R [k], R [k + 1],…, R [m]} and {R [m + 1], R [m + 2],…, R [h]}, merge them into an ordered subsequence:
{DR [l], DR [l + 1],…, DR [m], DR [m + 1],..., DR [h]}
2. Example
3. Implementation Code:
//// Main. cpp // CHelloWorld /// Created by IDEA-MAC03 on 13-12-16. // Copyright (c) 2013 IDEA-MAC03. all rights reserved. // # include
# Include
# Define SIZE 15 // The void MergeOne (int a [], int B [], int n, int len) function that completes the merge operation. {int I, j, k, s, e; s = 0; while (s + len <n) {e = s + 2 * len-1; if (e> = n) {e = n-1 ;} // adjacent ordered merge k = s; I = s; j = s + len; while (I <s + len & j <= e) {if (a [I] <= a [j]) {B [k ++] = a [I ++];} else {B [k ++] = a [j ++] ;}} while (I <s + len) {B [k ++] = a [I ++];} while (j <= e) {B [k ++] = a [j ++];} s = e + 1;} if (s
Running result:
Reference books: C/C ++ common algorithm manuals, data structures-yan Weimin, Tsinghua University