1.基本思想
将待排序的元素序列分为2个长度相等的子序列,对每一个子序列排序,然后将它们合并成一个序列,合并两个子序列的过程称为二路归并。
【该图转载博主一像素】
2.时间复杂度
由于归并排序不依赖于待排序元素序列的初始输入状态,每次划分两个子序列的长度基本一致,所以归并排序的最好,最差和平均时间复杂度均为O(n*log2n).
3.空间复杂度O(N)
4.稳定
5.代码
1)递归
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<string.h>
//归并排序合并过程
void Merge(int* num, int start1, int end1, int start2, int end2, int* tmp)
{
assert(num&&tmp);
int begin = start1;
int index = start1;//从start1的地方合并
//和两条有序单链表的合并的过程类似
while ((start1 <= end1) && (start2 <= end2))
{
if (num[start1] < num[start2])
{
tmp[index++] = num[start1++];
}
else
{
tmp[index++] = num[start2++];
}
}
//把剩余的合并到tmp上
while (start1 <= end1)
tmp[index++] = num[start1++];
while (start2 <= end2)
tmp[index++] = num[start2++];
//tmp是个临时空间,最后到把合并的内容拷贝到num上
memcpy(num + begin, tmp + begin, sizeof(int)*(end2 - begin + 1));
}
//归并排序分开过程(递归树按照前序路线展开)
void _MergeSort(int* num, int begin, int end, int* tmp)
{
assert(num&&tmp);
int mid = begin + (end - begin) / 2;
//只有一个元素,说明这个序列已经有序
if (begin == end)
return;
//子问题划分左子序列
_MergeSort(num, begin, mid, tmp);
//子问题划分右子序列
_MergeSort(num, mid + 1, end, tmp);
//合并两个有序数组
Merge(num, begin, mid, mid + 1, end, tmp);
}
//
void MergeSort(int* num, int len)
{
if (num == NULL || len <= 0)
return;
//开辟临时空间,用来存放每次合并后的子序列
int* tmp = (int*)malloc(sizeof(int)*len);
_MergeSort(num, 0, len - 1, tmp);
//释放空间
free(tmp);
tmp = NULL;
}
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int main()
{
int arr[] = { 4, 1,6,8,5,2 };
int length = sizeof(arr) / sizeof(arr[0]);
printf("排序前:");
for (int i = 0; i<length; i++)
{
printf(" %d", arr[i]);
}
MergeSort(arr, length);
printf("\n排序后:");
for (int i = 0; i<length; i++)
{
printf(" %d", arr[i]);
}
printf("\n");
system("pause");
return 0;
}
2)非递归
//[left,right]
void MergeSortNR(int *a, int left, int right)
{
int begin = 0;
int end = 0;
int mid = 0;
//gap是两个要和并分组其中一个的步长。
for (int gap = 1;gap<=(right-left+1);gap*=2)
{
begin = left;
while (1)
{
mid = begin + gap - 1;
end = begin + 2 * gap - 1;
//mid>right剩下的不足一个组,肯定已经有序,因为gap是从1增长的。
if (mid>right)
{
break;
}
//中间值没有超,右边界超了,[begin,mid] [mid,right]
if (end > right)
{
end = right;
}
MergeNR(a, begin, mid, mid + 1, end);
begin = end + 1;
}
}
}
void MergeNR(int *a, int begin1, int end1,int begin2, int end2)
{
int *tmp = new int[end2 - begin1 + 1];
int left = begin1;
int right = end2;
int index = 0;
while (begin1 <= end1&&begin2 <= end2)
{
while (begin1 <= end1&&a[begin1] <= a[begin2])
{
tmp[index++] = a[begin1++];
}
while (begin2 <= end2&&a[begin1] > a[begin2])
{
tmp[index++] = a[begin2++];
}
}
while (begin2 <= end2&&begin1 > end1)
{
tmp[index++] = a[begin2++];
}
while (begin1 <= end1&&begin2 > end2)
{
tmp[index++] = a[begin1++];
}
for (int i = left, j = 0; i <= right; i++, j++)
{
a[i] = tmp[j];
}
delete[] tmp;
}