归并排序问题
归并排序问题的思路是,首先把待排序的数组分成左右两组,
然后将左边一组和右边一组先分别排序
最后合并。
具体实现用了递归和分治的方法。
#include<iostream>
using namespace std;
int a[100];
void merge(int left,int mid,int right)
{
int n1=mid-left+1;
int n2=right-mid;
int *al=new int[n1+1];
int *ar=new int[n2+1];
int m1=1,m2=1;
for(int i=left;i<=mid;++i)
al[m1++]=a[i];
for(int i=mid+1;i<=right;++i)
ar[m2++]=a[i];
m1=1;
m2=1;
for(int i=left;i<=right;++i)
{
if(m1<=n1&&m2<=n2)
{
a[i]=al[m1]<ar[m2]?al[m1++]:ar[m2++];
}
else
{
if(m1<=n1)
{
a[i]=al[m1++];
}
if(m2<=n2)
{
a[i]=ar[m2++];
}
}
}
}
void mergeSort(int left,int right)
{
if(left<right)
{
int l=(left+right)/2;
mergeSort(left,l);
mergeSort(l+1,right);
merge(left,l,right);
}
}
int main()
{
while(1)
{
int n;
cout<<"请输入数组个数,输入0表示结束"<<endl;
cin>>n;
if(n==0)
break;
for(int i=1;i<=n;++i)
cin>>a[i];
cout<<"排序前"<<endl;
for(int i=1;i<=n;++i)
cout<<a[i]<<" ";
cout<<endl;
cout<<"排序后"<<endl;
mergeSort(1,n);
for(int i=1;i<=n;++i)
cout<<a[i]<<" ";
cout<<endl;
}
}