排序算法之归并排序

来源:互联网 发布:sql修改字段长度 编辑:程序博客网 时间:2024/04/29 04:12

今天学习了其它大牛的归并算法分析和例程,然后参照相应资料,也写了个非递归实现的归并算法,记录下来,便于自己以后的复习:

template<class T>
void Merge(T src[],T dest[],int iSrcStart, int iSrcEnd,int iSrcArrLength)//因为src中含有两个分别有序的序列,所以需要传入参数告知两个序列的起始
{
 int i=iSrcStart-1;
 int k=iSrcStart;//dest index
 int j=iSrcEnd+1;
 for(;iSrcStart<=iSrcEnd&&j<=iSrcArrLength;k++)
 {
  if (src[iSrcStart] < src[j])
  {
   dest[k]=src[iSrcStart++];
  }
  else
  {
   dest[k] = src[j++];
  }
 }

 int l=0;
 if (iSrcStart <= iSrcEnd)
 {
  for (;l<=iSrcEnd-iSrcStart;l++)
  {
   dest[k+l]=src[iSrcStart+l];
  }
 }

 if (j<=iSrcArrLength)
 {
  for (l=0;l<=iSrcArrLength-j;l++)
  {
   dest[k+l]=src[j+l];
  }
 }
}

/************************************************************************/
/* 将src中相邻长度为 iMergeLength的序列两两归并到dest中                                                                    */
/************************************************************************/
template<class T>
void MergePass(T src[],T dest[],int iMergeLength, int iSrcLength)
{
 int i=0;
 int j=0;
 while(i<iSrcLength-2*iMergeLength+1)
 {
  Merge(src,dest,i,iMergeLength+i-1,2*iMergeLength+i-1);
  i+=2*iMergeLength;
 }

 if (iSrcLength-i+1> iMergeLength)
 {
  Merge(src,dest,i,iMergeLength+i-1,iSrcLength);
 }
 else
 {
  for (j=i;j<=iSrcLength;j++)
  {
   dest[j]=src[j];
  }
 }


}
//归并-非递归
template<class T>
void MergeSort(T srcArr[],int iArrLength)
{
 int i=1;
 int j=0;
 int k=1;
 T* tmp = new T[iArrLength+1];
 memset(tmp,0,sizeof(T)*(iArrLength+1));
 while(k<iArrLength)
 {
  MergePass(srcArr,tmp,k,iArrLength);
  k=2*k;

  MergePass(tmp,srcArr,k,iArrLength);
  k=k*2;
 }

 delete[] tmp;
}

int main(int argc, char *argv[])
{

 
 int a[9]={1,3,6,7,4,8,5,2,9};
 double b[10]={1.0,10.0,2.0,5.0,6.0,4.0,3.0,8.0,7.0,9.0};

 MergeSort(a,8);
 MergeSort(b,9);
 return 0 ;
  
}

 

这个对于内置类型的归并有效,自定义类型需要修改。