#include <iostream>
#include <time.h>
using namespace std;
void merge_bxy(int *a,int low,int mid,int high)
{
int p;
int i=low;
int j=mid+1;
int k=low;
int *temp = new int[high+1];
memset(temp,0,sizeof(int)*(high+1));
//前一半和后一半进行归并
for(;i<=mid && j<=high; k++)
{
if(a[i]<a[j])
{
temp[k]=a[i++];
}
else
{
temp[k]=a[j++];
}
}
if(i <= mid)
{
for(p=0; p<=mid-i; p++)
{
temp[k+p]=a[i+p];
}
}
if(j <= high)
{
for(p=0; p<=high-j; p++)
{
temp[k+p]=a[j+p];
}
}
for(p=low; p<=high; p++)
{
a[p]=temp[p];
}
}
void Msort(int *a,int low,int high)
{
if(low < high)
{
int mid = (low+high)/2;
Msort(a,low,mid);
Msort(a,mid+1,high);
merge_bxy(a,low,mid,high);
}
}
void print(int a[],int n)
{
for(int i=0; i<n; i++)
{
cout<<a[i]<<" ";
}
cout << endl;
}
void main()
{
int a[10];
srand((unsigned)time(NULL));//初始化随机数
for(int i=0; i<10; i++)
{
a[i]=rand()%20;
}
cout << "排序前:";
print(a,sizeof(a)/sizeof(a[0]));
int n=sizeof(a)/sizeof(a[0]);
Msort(a,0,n-1);
cout << "排序后:";
print(a,sizeof(a)/sizeof(a[0]));
}
【基础排序】归并排序
最新推荐文章于 2024-08-12 19:32:44 发布