在严蔚敏的数据结构中的链表部分就写了归并排序,在10.5中也实现了归并排序,只是是对一个未排序数组进行的例如未排序数组49,38,65,97,76,13,27,49.首先是要对该数组进行分割,对分割的进行排序,也就是2路归并排序。代码实现如下:
#include<iostream>
using namespace std;
void Merge(int *a,int *temp,int low,int mid,int high)//这个是以mid为界对mid前后的数组进行归并排序
{
int i=low,j=mid+1;
int k=0;
while(i<=mid&&j<=high)
{
if(a[i]<=a[j])
temp[k++]=a[i++];
else temp[k++]=a[j++];
}
while(i<=mid)
temp[k++]=a[i++];
while(j<=high)
temp[k++]=a[j++];
for(int v=low,k=0;v<=high;++k,++v)
a[v]=temp[k];
}
void MSort(int *a,int *temp,int low,int high)//这个是将数组进行分割
{
if(low<high)
{
int mid=(low+high)/2;
MSort(a,temp,low,mid);
MSort(a,temp,mid+1,high);
Merge(a,temp,low,mid,high);
}
}
void MergeSort(int *a,int len)
{
int *TR=new int[len];//注意用完要释放内存
MSort(a,TR,0,len-1);
delete []TR;
}
int main()
{
int a[]={49,38,65,97,76,13,27,49};
int len=sizeof(a)/sizeof(*a);
MergeSort(a,len);
for(int i=0;i<len;i++)
cout<<a[i]<<" ";
return 0;
}
其实很多时候看看别人写的代码可以提高很多。