合并排序算法是用分治策略实现对n个元素进行排序的算法。其基本思想是:将待排序的元素分成大小大致相同的两个子集合,分别对两个子集合进行排序,最终排好序的子集合并成所要求的排好序的集合。
#include<iostream>
using namespace std;
void mergePass(int x[],int y[],int s,int n);
void merge(int c[],int d[],int l,int m,int r);
void mergeSort(int a[],int n)
{
int *b = new int[n];
int s = 1;
while(s<n)
{
mergePass(a,b,s,n);//合并到数组b
s+=s;
mergePass(b,a,s,n);//合并到数组a
s+=s;
}
for(int an=0;an<5;an++)
cout<<a[an]<<" ";
for(an=0;an<5;an++)
cout<<b[an]<<" ";
}
void mergePass(int x[],int y[],int s,int n)
{//合并大小为s的相邻子数组
int i = 0;
while(i<=n-2*s)
{//合并大小为s的相邻2段子数组
merge(x,y,i,i+s-1,i+2*s-1);
i = i+2*s;
}
//剩下的元素个数少于2s
if(i+s<n)
merge(x,y,i,i+s-1,n-1);
else for(int j = i;j<= n-1;j++) y[j] = x[j];
}
void merge(int c[],int d[],int l,int m,int r)
{//合并数组
int i = l,j = m+1,k = l;
while(i<=m&&j<=r)
if(c[i]<=c[j]) d[k++] = c[i++];
else d[k++] = c[j++];
if(i>m) for(int q = j;q<=r;q++) d[k++] = c[q];
else for(int q = i;q<=m;q++) d[k++] = c[q];
}
int main()
{
int arr[5]={100,25,3,1,7};
mergeSort(arr,5);
return 0;
}