#include<stdlib.h>
#include<stdio.h>
using namespace std;
void Merge(int* src,int * des,int low,int mid,int hight)
{
int i = low;
int j = mid + 1;
int k = low;
while (i<=mid&&j<=hight)//将小的梵高目的地中
{
if (src[i]<src[j])
{
des[k++] = src[i++];
}
else
{
des[k++] = src[j++];
}
}
while (i<=mid)//若还剩几个尾部元素,加到后面
{
des[k++] = src[i++];
}
while (j <= hight)
{
des[k++] = src[j++];
}
}
//每次分为两路。当只剩下一个元素时,就不需要再划分
void MSort(int* src, int* des, int low, int high,int max)
{
if (low==high)
{
des[low] = src[low];
}
else//如果多个元素,进行两路划分
{
int mid = (low + high) / 2;
int* space = (int*)malloc(sizeof(int)*max);
//递归进行两路的划分,当剩下一个元素的时候,递归划分结束,然后开始merge归并操作
if (space!=NULL)
{
MSort(src,space,low,mid,max);
MSort(src, space, mid+1, high, max);
Merge(space, des, low, mid, high);
}
free(space);
}
}
void MergeSort(int * arry,int count)
{
MSort(arry,arry,0,count-1,count);
}
void main()
{
int arry[] = { 12,20,45,25,35,1,2,54,52 };
int count = sizeof(arry) / sizeof(*arry);
printf("arry数组个数:%d\n", count);
for (int i = 0; i < count; i++)
{
printf("%d ", arry[i]);
}
printf("\n排序之前");
MergeSort(arry, count);
for (int i = 0; i < count; i++)
{
printf("%d ", arry[i]);
}
printf("\n排序之后");
system("pause");
}
排序算法—归并排序
最新推荐文章于 2024-08-12 19:32:44 发布