Merge sort uses the "merge" Technology for sorting. Merging refers to merging several sorted sub-files into an ordered file.
Merge two channelsAlgorithm
1. Basic algorithm ideas
Set two ordered sub-files (equivalent to the input heap) to the adjacent positions in the same vector: R [low .. m], R [M + 1 .. high], first merge them into a local temporary storage vector r1 (equivalent to the output heap), and then copy R1 back to R [low .. high.
(1) merging process
During the merge process, set the I, j, and P pointers, and their initial values point to the starting positions of the three record areas respectively. When merging, compare the keywords of R [I] and R [J] in sequence, and copy the records with smaller keywords to R1 [p, then add the pointer I or J of the copied record to 1 and the pointer P pointing to the copy position to 1.
Repeat this process until one of the two input sub-files has been completely copied (it may be called null ), copy the remaining records of another non-empty sub-file to R1.
(2) dynamically apply for r1
During implementation, R1 dynamically applies because the application space may be large, so it must be added to the application space for successful processing.
2. Merge Algorithms
Void Merge (seqlist R, int low, int M, int high)
{// Combine two ordered sub-files R [low.. m) and R [M + 1 .. High] into an ordered sub-File
// Sub-file R [low .. High]
Int I = low, j = m + 1, P = 0; // set the Initial Value
Rectype * R1; // R1 is a local vector. If P is defined as a pointer of this type, the speed is faster.
R1 = (reetype *) malloc (high-low + 1) * sizeof (rectype ));
If (! R1) // failed to apply for Space
Error ("insufficient memory available! ");
While (I <= M & J <= high) // when the two sub-files are not empty, the small ones are output to R1 [p ].
R1 [p ++] = (R [I]. Key <= R [J]. Key )? R [I ++]: R [J ++];
While (I <= m) // If the 1st sub-files are not empty, copy the remaining records to r1
R1 [p ++] = R [I ++];
While (j <= high) // If the 2nd sub-files are not empty, copy the remaining records to r1
R1 [p ++] = R [J ++];
For (P = 0, I = low; I <= high; P ++, I ++)
R [I] = R1 [p]; // after merging, copy the result back to R [low... high]
} // Merge