The rainy day may be nice! But the heart maybe low。。。
今天来学习一下归并排序
归并排序的主要操作是归并,其主要思想是:将若干有序序列逐步归并,最终得到一个有序序列。
归并:将两个或两个以上的有序序列合并成一个有序序列的过程。
将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并
二路归并排序:基本思想:将一个具有n个待排序记录的序列看成是n个长度为1的有序序列,然后进行两两归并,得到n/2个长度为2的有序序列,再进行两两归并,得到n/4个长度为4的有序序列,……,直至得到一个长度为n的有序序列为止。
当然归并排序是递归很好的例子。
首先来解决两个有序序列合成一个有序序列。
代码描述:
void Merge(int *A, int *tempArray, int Lpos, int Rpos,int RightEnd)
{
int i,LeftEnd,Num,Tempos;
LeftEnd=Rpos-1;
Tempos=Lpos;
Num=RightEnd-Lpos+1;
while(Lpos<=LeftEnd&&Rpos<=RightEnd)
{
if(A[Lpos]<=A[Rpos])
{tempArray[Tempos++]=A[Lpos++];}
else
{tempArray[Tempos++]=A[Rpos++];}
}
while(Lpos<=LeftEnd)
{tempArray[Tempos++]=A[Lpos++];}
while(Rpos<=RightEnd)
{tempArray[Tempos++]=A[Rpos++];}
for(i=0;i<Num;i++,RightEnd--)
{A[RightEnd]=tempArray[RightEnd];}
}
接着就是递归的去解决各个问题。
代码描述:
void Msort(int *A,int *tempArray,int left,int right)
{
int center;
if(left<right)
{
center=(left+right)/2;
Msort(A,tempArray,left,center);
Msort(A,tempArray,center+1,right);
Merge(A,tempArray,left,center+1,right);
}
}
这两个就是归并排序的主要算法。
该算法是经典的分治策略,它将问题分成一些小的问题然后递归求解,而治的阶段将分的阶段解得的各个答案修补到一起。
A little more for everyday.
在烈火中历练。