原理:
将一个序列进行拆分,直到不能拆分为止,分为(N个组),然后再将两组元素进行比较,排列成有序的组,直到组合成一个组。
举例:
31,12,5,57,2,31,90,32,95,76
拆分:
{31,12,5,57,2} {31,90,32,95,76}
拆分:
{31,12} {5,57,2} {31,90} {32,95,76}
拆分:
{31} {12} {5} {57,2}
{31} {90} {32} {95,76}
拆分:
{31} {12} {5} {57} {2}
{31} {90} {32} {95} {76}
合并:
{31} {12} {5} {2,57} {31} {90} {32} {76,95}
合并:
{12,31} {2,5,57} {31,90} {32,76,95}
合并:
{2,5,12,31,57} {31,32,76,90,95}
合并:
{2,5,12,31,31,32,57,76,90,95}
注:红色数字表示此时不会再拆分。
代码:
void Merge(int *l, int lsize, int *r, int rsize)
{
int i, j, k;
i = j = k = 0;
int temp[10];
while (i < lsize&&j<rsize)
{
if (l[i] < r[j])
temp[k++] = l[i++];
else
temp[k++] = r[j++];
}
while (i<lsize)
temp[k++] = l[i++];
while (j<rsize)
temp[k++] = r[j++];
for (int m = 0; m != k; ++m)
{
l[m] = temp[m];
}
}
void MergeSort(int a[],int nlen)
{
if (nlen>1)
{
int *left = a;
int left_size = nlen / 2;
int *right = a + left_size;
int right_size = nlen - left_size;
MergeSort(left, left_size);
MergeSort(right, right_size);
Merge(left, left_size, right, right_size);
}
}
总结:
归并排序算法的思想很简单,没有过多的因素干扰待排序序列,是稳定的排序算法。时间复杂度为O(Nlog2N)。