#include<iostream>
using namespace std;
int a[100];
int b[100];
void Merge(int left,int middle,int right)
{
int i=left,j=middle+1,k=left;
while(i<=middle&&j<=right)
{
if(a[i]<=a[j])
{
b[k++]=a[i];
i++;
}
else
{
b[k++]=a[j];
j++;
}
}
while(i<=middle)
{
b[k++]=a[i];
i++;
}
while(j<=right)
{
b[k++]=a[j];
j++;
}
for(int i=left;i<=right;i++)
a[i]=b[i];
}
void MergeSort(int left,int right)
{
if(left<right)
{
int middle=(left+right)/2;
MergeSort(left,middle);
MergeSort(middle+1,right);
Merge(left,middle,right);
}
}
int main()
{
int n;cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"排序前:";
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
MergeSort(0,n-1);
cout<<"排序后:";
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
合并排序(归并排序)
最新推荐文章于 2024-08-26 21:33:46 发布