对于分别有序的两段序列,调用Merge后形成的序列也是有序的,通过“递”不断地将每一个子列拆分为两个子列,拆到最后,形成的两个子列都只有一个元素,这时候两段子列显然是有序的,于是在“归”的过程中,不断地用Merge合并子列,最后形成有序列。
递归实现的算法抄的严蔚敏《数据结构》树上的。
//
// Created by dgm on 19-4-24.
//
#include <iostream>
using namespace std;
typedef int KeyType;
typedef char* Info;
typedef struct {
KeyType key;
Info info;
}RcdType;
void Merge(RcdType SR[],RcdType TR[],int i,int mid,int n)
{
int j,k,l;
for (j = i,k=mid+1,l=i; j <= mid&&k <= n; ) {
if (SR[j].key>SR[k].key)TR[l++]=SR[k++];
else
TR[l++]=SR[j++];
}
if (j<=mid)
for ( ; j <=mid ; )
TR[l++]=SR[j++];
if (k<=n)
for ( ; k <=n ; )
TR[l++]=SR[k++];
}
void MergeSort(RcdType SR[],RcdType TR1[],int s,int t)
{
int mid;
RcdType TR2[7];
if (s==t) TR1[s]=SR[s];
else{
mid=(t+s)/2;
MergeSort(SR,TR2,s,mid);
MergeSort(SR,TR2,mid+1,t);
Merge(TR2,TR1,s,mid,t);
}
}
int main()
{
RcdType r[6+1];
for (int i = 1; i <= 6; ++i) {
r[i].key=rand()%100;
}
MergeSort(r,r,1,6);
for (int i = 1; i <= 6; ++i) {
cout<<r[i].key<<" ";
}
return 0;
}
非递归实现抄的《大话数据结构》上的
//
// Created by dgm on 19-4-23.
//
#include <iostream>
using namespace std;
typedef int KeyType;
typedef char* Info;
typedef struct {
KeyType key;
Info info;
}RcdType;
void Merge(RcdType SR[],RcdType TR[],int i,int mid,int n)
{
int j,k,l;
for (j = i,k=mid+1,l=i; j <= mid&&k <= n; ) {
if (SR[j].key>SR[k].key)TR[l++]=SR[k++];
else
TR[l++]=SR[j++];
}
if (j<=mid)
for ( ; j <=mid ; j++)
TR[l++]=SR[j];
if (k<=n)
for ( ; k <=n ; k++)
TR[l++]=SR[k];
}
void MergePass (RcdType SR[],RcdType TR[],int s,int n)
{
int i=1;
while (i<=n+1-2*s){
Merge(SR,TR,i,i+s-1,i+2*s-1);
i+=2*s;
}
if (i<n+1-s){
Merge(SR,TR,i,i+s-1,n);
}
else
for (; i <= n ; ++i)//这里如果去掉++i,而将下一行改为
TR[i]=SR[i]; //TR[i++]=SR[i++]就不对了,这是为什么?
}
void MergeSort2(RcdType *SR)
{
RcdType temp[7];
int k=1;
while (k<6){
MergePass(SR,temp,k,6);
k*=2;
MergePass(temp,SR,k,6);
k*=2;
}
}
int main()
{
RcdType r[6+1];
for (int i = 1; i <= 6; ++i) {
r[i].key=rand()%100;
}
MergeSort2(r);
for (int j = 1; j <= 6; ++j) {
cout<<r[j].key<<" ";
}
return 0;
}