Merge sorting method: Merge two (or more) ordered lists into a new ordered list, that is, divide the sequence to be sorted into several subsequences, and each subsequence is ordered. Then, the ordered subsequences are merged into the overall ordered sequence. A division process is always called
during the execution process until the subsequence is empty or has only one element. A total of log2n recursion is required. In the process of merging, the merge length is 2. , 4... until the whole sequence is ordered
Merge icon
Merge realization
#define MAXSIZE 20 //默认定义数据大小为20
#define T int
typedef T Seqlist[MAXSIZE];
void merge(Seqlist &L,Seqlist &sq,int left,int mid,int right)//合并
{
for(int i = left;i<=right;++i) //赋值
{
sq[i] = L[i];
}
int s1 = left;
int s2 = mid + 1;
int k = left;
while(s1<=mid && s2 <=right)
{
if(sq[s1]<=sq[s2])
{
L[k++] = sq[s1++];
}
else
{
L[k++]= sq[s2++];
}
}
while(s1 <= mid)//左边还有值,而右边已经到达界限
{
L[k++] = sq[s1++];
}
while(s2 <= right)
{
L[k++] = sq[s2++];
}
}
void Merge_sort(Seqlist &L,Seqlist &sq,int left,int right)
{
if(left >= right)
return;
int mid = (left + right)/2;//将数据分为两部分
Merge_sort(L,sq,left,mid);//对左边数据进行归并排序
Merge_sort(L,sq,mid+1,right);//对右边数据进行归并排序
merge(L,sq,left,mid,right);//将左右两部分数据进行合并
}
merged test files
void main() //归并排序测试
{
Seqlist L = {16,33,9,8,25,21,3,49,5};
Seqlist sq;
int n = 9;
Merge_sort(L,sq,0,8);
for(int i = 0;i < n;++i)
{
cout<<L[i]<<" ";
}
}
The main problem with merge sort is that it requires an auxiliary space as large as the original data. Merge sort is a stable sorting method.