1.算法思想
首先,将R[0…n-1]看成是n个长度为1的有序表,将相邻的有序表成对归并,得到n/2个长度为2的有序表;然后,再将这些有序表成对归并,得到4/n个长度为4的有序表,如此反复进行下去,最后得到一个长度为n的有序。
由于归并是在相邻的两个有序表中进行的,因此,上述排序方法也叫二路归并排序。如果归并操作是在相邻的多个有序表中进行,则叫多路归并排序。这里只讨论二路归并排序。
2.算法过程
(1)Merge()
该算法用于将两个有序表归并为一个有序表。
void Merge(int a[], int low, int mid, int high) {
//申请一个额外空间,用来暂存归并的结果
int *temp = new int[high-low+1];
int i=low, j=mid;
int m=mid+1, n=high;
int k=0;
//在两个有序表中从前往后扫描
while(i<=j && m<=n) {
if(a[i]<=a[m])
temp[k++] = a[i++];
else
temp[k++] = a[m++];
}
//将前一个有序表中剩余的数据暂存到temp中
while(i<=j)
temp[k++] = a[i++];
//将后一个有序表中剩余的数据暂存到temp中
while(m<=n)
temp[k++] = a[m++];
//将temp中的数据覆盖原来的数组
for(i=0;i<k;++i)
a[low+i] = temp[i];
delete[] temp;
}
(2)归并排序——分而治之
算法的过程见下图:
void merge_sort(int a[], int low, int high) {
//只有一个或无记录时不须排序
if(low>=high) return;
//取中间位置
int mid = (low+high)>>1;
//递归分治
merge_sort(a,low,mid);
merge_sort(a,mid+1,high);
//归并
Merge(a,low,mid,high);
}
3.性能分析
归并排序的时间效率与待排序的数据序列的顺序无关。
(1)时间复杂度:
- 平均 O(nlog2n)
- 最好情况 O(nlog2n)
- 最坏情况 O(nlog2n)
(2)空间复杂度:O(n)
(3)稳定性:稳定
(4)复杂性:较复杂
4.完整代码
#include<iostream>
using namespace std;
//合并两个有序表,并存储到
void Merge(int a[], int temp[], int low, int mid, int high) {
int i=low, j=mid;
int m=mid+1, n=high;
int k=0;
while(i<=j && m<=n) {
if(a[i]<=a[m])
temp[k++] = a[i++];
else
temp[k++] = a[m++];
}
while(i<=j)
temp[k++] = a[i++];
while(m<=n)
temp[k++] = a[m++];
for(i=0;i<k;++i)
a[low+i] = temp[i];
}
void msort(int a[], int temp[], int low, int high) {
if(low>=high) return;
int mid = (low+high)>>1;
msort(a,temp,low,mid);
msort(a,temp,mid+1,high);
Merge(a,temp,low,mid,high);
}
void merge_sort(int a[], int len) {
int *temp = NULL;
temp = new int[len];
if(temp!=NULL){
msort(a,temp,0,len-1);
delete[] temp;
}
}
int main() {
int a[8] = {50,10,90.30,70,40,80,60,20};
merge_sort(a,8);
for(int i=0;i<8;++i)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
运行结果