
/**//*
书上采用的是更现实的非递归算法,但是我参考了几本书都是采用的递归算法,并且书上的非递归算法也没有太细的讲(可能是我太笨吧),总之
没有学明白.唉
:(
这里采用的是严蔚敏版的递归算法,且在这本书中,也有提示说递归算法在实际应用中不可取,因为在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;
}