
/**//*
书上采用的是更现实的非递归算法,但是我参考了几本书都是采用的递归算法,并且书上的非递归算法也没有太细的讲(可能是我太笨吧),总之
没有学明白.唉
:(
这里采用的是严蔚敏版的递归算法,且在这本书中,也有提示说递归算法在实际应用中不可取,因为在MSort要重复的定义很多的list,需要很多的栈空间
自考书中的算法只需要定义一个list.我也纳闷了,连正规的本科讲的归并都是采用的递归算法,为什么自考的居然用非递归的
..
*/
#include "stdafx.h"
#include <iostream.h>
#include <malloc.h>

int const count=8;

typedef struct


{
int key;
}records;

typedef records list[count+1];

//将s中的s[i..m]和s[m+1..n]归并到r[i..n]中
void Merge(list & s,list & t,int i,int m,int n)


{
int j=m+1;
int k=i;
while(i<=m && j<=n)

{
if (s[i].key<s[j].key)

{
t[k].key=s[i].key;
i++;
}
else

{
t[k].key=s[j].key;
j++;
}
k++;
}
while(i<=m)

{
t[k].key=s[i].key;
i++;
k++;
}
while(j<=n)

{
t[k].key=s[j].key;
j++;
k++;
}
}

void MSort(list & sr,list & tr,int s,int t)


{
if (s==t)

{
tr[s].key=sr[s].key;
}
else

{
list t2;
int m=(s+t)/2;
MSort(sr,t2,s,m);
MSort(sr,t2,m+1,t);
Merge(t2,tr,s,m,t);
}
}

void printList(list r)


{
for(int i=0;i<count;i++)

{
if (i==0)

{
cout<<r[i+1].key;
}
else

{
cout<<","<<r[i+1].key;
}
}
cout<<endl;
}

int main(int argc, char* argv[])


{
list r;

/**//*
for(int i=0;i<count;i++)
{
cout<<"输入第"<<i+1<<"个主键";
cin>>r[i+1].key;
}
*/
r[1].key=70;
r[2].key=73;
r[3].key=69;
r[4].key=23;
r[5].key=93;
r[6].key=18;
r[7].key=11;
r[8].key=68;
cout<<"输入的序列为:"<<endl;
printList(r);
list tr;
MSort(r,tr,1,count);

cout<<"快速排序后的序列为:"<<endl;
printList(tr);
return 0;
}
一点说明:为什么在标题中要嵌入英文?原因是为了能够让国外的网友能查询到这篇文章。平常在Google上查资料的时候,经常参考国外网友的博客,帮助我解决了很多问题,所以我也想让他们能够参考我写的内容。当然文中我不可能全部译为英文,所以我尽量把代码粘全,靠代码说话吧。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步