Merge Sorting(Merging
Is another type of sorting method. "Merge" means to combine two or more ordered tables into a new ordered table. Time Complexity:O (nlog2n).
Const Int Count = 9 ;
// 2-recursive form of Merge Sorting
Void Cmergingsort: path2mergingsort ( Void )
{
Int L [count] = { 0 , 49 , 38 , 65 , 97 , 76 , 13 , 27 , 49 };
Msort (l, l, 1 , Count - 1 );
// Print the sorting result.
For ( Int I = 0 ; I < Count; ++ I)
{
Cout < L [I] < " \ T " ;
}
Cout < Endl;
}
// 2-merge in recursive form of merge sort
Void Cmergingsort: Merge ( Int Sr [], Int Tr [], Int I, Int M, Int N)
{
// Merge ordered Sr [I. m] AND Sr [M + 1. N] into ordered tr [I. N]
Int J = 0 , K = 0 ;
For (J = M + 1 , K = I; I <= M && J <= N; ++ K)
{
// Merge Records in SR from small to large into tr
If (Sr [I] <= Sr [J])
Tr [k] = Sr [I ++ ];
Else
Tr [k] = Sr [J ++ ];
}
While (I <= M) tr [K ++ ] = Sr [I ++ ]; // Copy the remaining SR [I. m] to tr
While (J <= N) tr [K ++ ] = Sr [J ++ ]; // Copy the remaining SR [J. N] to tr
}
// 2-recursive form of merge sort
Void Cmergingsort: msort ( Int Sr [], Int Tr1 [], Int S, Int T)
{
// Sort Sr [S. T] into tr1 [S. T]
If (S = T)
Tr1 [s] = Sr [s];
Else
{
Int Tr2 [count] = { 0 }; // If the data volume is large, will it occupy too much storage space ??
Int M = (S + T) / 2 ; // Divide Sr [S. T] into Sr [S. M] AND Sr [M + 1. T]
Msort (Sr, tr2, S, M ); // Recursively merge Sr [s .. m] into an ordered tr2 [s .. m]
Msort (Sr, tr2, m + 1 , T ); // Recursively merge Sr [M + 1. T] into an ordered tr2 [M + 1. T]
Merge (tr2, tr1, S, M, t ); // Merge tr2 [s .. m] And tr2 [M + 1 .. t] To tr1 [s .. t]
}
}
In the msort function, int tr2 [count] = {0}; of the else statement will apply for an array of the same size as the original array during recursive calling, because it is only a simple array, therefore, the memory is automatically released at the end of the current function. Does it occupy too much storage space? When a large amount of data is required, perform the test.