1、算法原理
歸併排序(mergesort)以O(NlogN)最壞情形運行時間運行,而使用的比較次數幾乎是最優的。它是遞歸算法一個很好的實例。
算法的基本操作就是合併兩個已排序的表。因爲兩個表是已排序的,所以若將輸出放到第三個表中時則該算法可以通過對輸入數據一趟排序來完成。
2、代碼
/*+++++++++++++++++++++++++++++++++++++
+ 歸併排序(C版)
+
+author:zhouyongxyz 2013-4-15 9:16
+++++++++++++++++++++++++++++++++++++*/
#include <cstdio>
#include <cstdlib>
#define N 8
typedef int ElementType;
void Merge(ElementType a[],ElementType tmp[],int lpos,int rpos,int rightEnd); //將已知的兩個已排序的數組進行合併。
void MSort(ElementType a[],ElementType tmp[],int left,int right); //遞歸調用實現數組的合併操作。
void MergeSort(ElementType a[],int n); //歸併排序
int main()
{
int a[N]={4,3,5,2,9,7,6,8};
MergeSort(a,N);
for(int i=0;i<N;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
void MergeSort(ElementType a[],int n)
{
ElementType *tmp=(ElementType*)malloc(n*sizeof(ElementType));
if(tmp!=NULL)
MSort(a,tmp,0,n-1);
}
void MSort(ElementType a[],ElementType tmp[],int left,int right)
{
if(left<right)
{
int center=(left+right)/2;
MSort(a,tmp,left,center);
MSort(a,tmp,center+1,right);
Merge(a,tmp,left,center+1,right);
}
}
void Merge(ElementType a[],ElementType tmp[],int lpos,int rpos,int rightEnd)
{
int tpos=0;
int leftEnd=rpos-1;
int numElements=rightEnd-lpos+1;
while(lpos<=leftEnd&&rpos<=rightEnd)
{
if(a[lpos]<=a[rpos])
tmp[tpos++]=a[lpos++];
else
tmp[tpos++]=a[rpos++];
}
while(lpos<=leftEnd)
tmp[tpos++]=a[lpos++];
while(rpos<=rightEnd)
tmp[tpos++]=a[rpos++];
for(int i=numElements-1;i>=0;i--,rightEnd--)
a[rightEnd]=tmp[i];
}