原理
将序列两两分组,然后归并为[n/2]个组,组内单独排序,然后将这些组归并为[n/4]个组,组内单独排序,以此类推,直到只剩一个组为止
例:
要将序列{66,12,33,57,64,27,18}进行2-路归并
①第一趟 两两分组,得到四个组{66,12}、{33,57}、{64,27}、{18},组内单独排序,得到{{66,12},{33,57},{64,27},{18}}
②第二趟,将四个组两两分组,得到两个组{12,66,33,57},{27,64,18}组内单独排序,得到{{12,33,57,66}, {18,27,64}}
③将两个组继续两两分组,得到一组{12,33,57,66,18,27,64},组内单独排序,得到{12,18,27,33,57,64,66},算法结束
以下是2-路归并动态排序图,有助于更好理解
思路
算法的设计思路就是将一个数组,中间切一刀,分成左右两部分,左部分中间切一刀,又分成两部分,继续切……直到子区间内仅剩下一个元素时,切分结束,返回上一步,返回后区间内就有俩元素了,然后排序,再返回上一步,在排序,直到该区间就是整个数组时,排序,结束。
很容易看出来这是递归的思想,其中,排序可以由two Pointers算法进行排序(什么是twoPointers?)
代码
下面给出排序代码
void _merge(int A[], int L1, int R1, int L2, int R2) //L2 = R1 +1
{
int C[maxn];
int i = L1, j = L2;
int index = 0;
while(i <= R1 && j <= R2)
{
if(A[i] <= A[j])
C[index++] = A[i++];
else
C[index++] = A[j++];
}
while(i<= R1) C[index++] = A[i++];
while(j<= R2) C[index++] = A[j++];
for(int k = L1; k<= R2; k++)
{
A[k] = C[k];
printf("%d ",A[k]);
}
}
/*
int main()
{
int A[7] = {12,33,57,66,18,27,64};
_merge(A, 0, 3, 4, 6);
return 0;
}
*/
排序的问题解决了,然后解决归并问题,
void mergeSort(int A[], int left, int right)
{
int mid = left + (right - left) /2;
if(left< right)
{
mergeSort(A,left, mid);
mergeSort(A,mid+1, right);
_merge(A, left, mid, mid+1, right);
}
}
完整代码
#include <iostream>
#include<cstdio>
using namespace std;
const int maxn = 11;
void _merge(int A[], int L1, int R1, int L2, int R2) //L2 = R1 +1
{
int C[maxn];
int i = L1, j = L2;
int index = 0;
while(i <= R1 && j <= R2)
{
if(A[i] <= A[j])
C[index++] = A[i++];
else
C[index++] = A[j++];
}
while(i<= R1) C[index++] = A[i++];
while(j<= R2) C[index++] = A[j++];
for(int k = 0; k< index; k++)
{
A[k+L1] = C[k];
//printf("%d ",A[k+L1]);
}
//printf("\n");
}
void mergeSort(int A[], int left, int right)
{
int mid = left + (right - left) /2;
if(left< right)
{
mergeSort(A,left, mid);
mergeSort(A,mid+1, right);
_merge(A, left, mid, mid+1, right);
}
}
int main()
{
int A[7] = {66,12,33,57,64,27,18};
mergeSort(A, 0,6);
for(int k = 0; k<7; k++)
{
printf("%d ",A[k]);
}
return 0;
}
sort函数排序
C++内置的sort函数时间复杂度应该是O(n*log2n)比twoPointers(O(n))要慢上不少
如果时间允许,把_merge()函数直接用sort替换也可以